简体   繁体   中英

List comprehension with conditional function inside

I want to write list comprehension with conditional function inside. This what i have so far

more_grades = [0.0, 50.0, 49.9, 79.0, 101.0, 65.0, 54.2, 48.2, 78.9]
def grade_classification(grade):
        if grade < 40:
            result = 'fail'
        elif grade >= 40 and grade < 50:
            result = 'Pass'
        elif grade >= 50 and grade < 60:
            result = '2:2'
        elif grade >= 60 and grade < 70:
            result= '2:1'
        elif grade >= 70:
            result = 'First'
        else:
            result = 'unknown grade'
        return result
studen_classficatin = [result for result in more_grades if grade_classification(result)]
print(studen_classficatin)

The output should be = ['Fail', '2:2', 'Pass', 'First', 'First', '2:1', '2:2', 'Pass', 'First'] but from the code above its giving me = [0.0, 50.0, 49.9, 79.0, 101.0, 65.0, 54.2, 48.2, 78.9] I dont know what i am doing wrong. Please any suggestion?

Change it to this instead:

studen_classficatin = [grade_classification(result) for result in more_grades]

The trailing if will determine whether or not an element should be added to the list, not "transform" the element itself

You don't really need to do list comprehension, instead you can apply map to your list to call a function on each entry of the list. The result will be an iterator that consists of the returned value for each value in your previous list:

studen_classficatin = map(grade_classification, more_grades)

map returns an iterator, so it doesn't actually do anything until you iterate over the list. If you want to print it, call list on the iterator to exhaust it:

studen_classficatin = list(map(grade_classification, more_grades))

Your code is this:

studen_classficatin = [result for result in more_grades if grade_classification(result)]

Which, because non-empty strings are truthy , is the same as:

studen_classficatin = [result for result in more_grades if True]

Which is the same as:

studen_classficatin = [result for result in more_grades]

which is the same as just copying more_grades .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM