Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

python - How to skip making a 'sentence(s)' if the the integer in the list is a zero?

I didn't know how to title this. It might've been a little confusing. If this is a duplicate, sorry; please lead me to the answer page.

In this example code, sometimes the "difference" is 0. How can I remove 'statements' that have 0 in them? (See below for details)

classlist = ['CLASS1', 'CLASS2', 'CLASS3', 'CLASS4', 'CLASS5', 'CLASS6', 'CLASS7']
gradelist1 = ['69.8', '73', '89', '0', '93', '57']
gradelist2 = ['95.3', '79', '84', '0', '68', '63']

def gradeChangeShow():
    difference = []
    try:
        for i in range(len(gradelist1)):
            difference.append(int(float(gradelist2[i])) - float(gradelist1[i]))
        difference = ["{:.1f}".format(x) for x in difference]
    except ValueError:
        difference.append('0')
    difference = [x for x in difference if x != '0']
    statement = [f'
{c.rstrip()}: {d}' for c, d in zip(classlist, difference)]
    comma_delete = ','.join(statement)
    return comma_delete.replace(',', '')

print(gradeChangeShow())

This is what comes out from the code above:

CLASS1: 25.2 
CLASS2: 6.0  
CLASS3: -5.0 
CLASS4: 0.0  
CLASS5: -25.0
CLASS6: 6.0

How I want it to come out:

CLASS1: 25.2 
CLASS2: 6.0  
CLASS3: -5.0 
CLASS5: -25.0
CLASS6: 6.0
question from:https://stackoverflow.com/questions/65926218/how-to-skip-making-a-sentences-if-the-the-integer-in-the-list-is-a-zero

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you tried to filter your results, you used an integer 0 value as the target. Since your values are strings with decimal points, there is no way this can ever work for you.

Instead, make sure you compare against the same types. You could filter against '0.0', but this will fail if you ever change the precision in your strings. I recommend that you convert the value to numeric, and compare against that.

statement = [f'
{c.rstrip()}: {d}'
               for c, d in zip(classlist, difference) if float(d) != 0]

Output:

CLASS1: 25.2
CLASS2: 6.0
CLASS3: -5.0
CLASS5: -25.0
CLASS6: 6.0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...