是否可以添加用于评估列表理解中的条件的函数

Bhu*_*ant 0 python if-statement list-comprehension

在列表理解中过滤子句,

作为一个特别有用的扩展,嵌套在复杂表达式中的for循环可以有一个关联的if子句来过滤掉测试不正确的结果项.

//This will return the list of all the even numbers in range 100
print [index for index in range(100) if 0 == index%2]
Run Code Online (Sandbox Code Playgroud)

但我正在寻找添加一个可以被调用来评估条件的函数的可能性.有了这个功能,我将能够在其中添加更复杂的条件.

像这样的东西,

def is_even(x):
    return 0 is x%2

print [index +100 for index in range(10) 0 is_even(index)]
Run Code Online (Sandbox Code Playgroud)

the*_*eye 5

是的,你可以很好地补充一点.该构造看起来类似于正常的过滤条件

def is_even(x):
    return 0 == x%2

print [index + 100 for index in range(10) if is_even(index)]
Run Code Online (Sandbox Code Playgroud)

只要函数返回truthy值1,过滤就会按预期工作.

注意:使用==检查,而不是使用两个值是否相等,is运营商.的is运算符用于检查被比较的对象是同一个.


1引用Python的官方文档,

在布尔运算的上下文中,以及控制流语句使用表达式时,以下值被解释为false : False, None所有类型的数字零,以及空字符串和容器(包括字符串,元组,列表,字典,集合)和frozensets).所有其他值都被解释为true.

因此,只要您的函数返回上述列表中提到的虚假项目以外的任何内容,就会满足条件.


除此之外,Python的List comprehension的语法允许您在其中包含多个if子句.例如,假设您要查找所有倍数3不是530的倍数,您可以这样写

>>> [index for index in range(30) if index % 3 == 0 if index % 5 != 0]
[3, 6, 9, 12, 18, 21, 24, 27]
Run Code Online (Sandbox Code Playgroud)

它会产生同样的效果

>>> [index for index in range(30) if index % 3 == 0 and index % 5 != 0]
[3, 6, 9, 12, 18, 21, 24, 27]
Run Code Online (Sandbox Code Playgroud)