简体   繁体   English

内部有条件 function 的列表理解

[英]List comprehension with conditional function inside

I want to write list comprehension with conditional function inside.我想用里面的条件 function 编写列表理解。 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. output 应该是 = ['Fail', '2:2', 'Pass', 'First', 'First', '2:1', '2:2', 'Pass', 'First'] 但来自上面的代码给我 = [0.0, 50.0, 49.9, 79.0, 101.0, 65.0, 54.2, 48.2, 78.9] 我不知道我做错了什么。 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尾随的if将确定是否应将元素添加到列表中,而不是“转换”元素本身

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.您实际上并不需要进行列表理解,而是可以将map应用于您的列表以在列表的每个条目上调用 function。 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. map返回一个迭代器,因此在您遍历列表之前它实际上不做任何事情。 If you want to print it, call list on the iterator to exhaust it:如果你想打印它,在迭代器上调用list来耗尽它:

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:其中,因为非空字符串是truthy ,所以与:

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 .这与复制more_grades相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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