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

Is it possible to add function for evaluating if condition in 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]

但我正在考虑添加一个可以调用以评估条件的函数的可能性。? 有了这个功能,我将能够在其中添加更复杂的条件。

像这样,

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

print [index +100 for index in range(10) 0 is_even(index)]

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

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

print [index + 100 for index in range(10) if is_even(index)]

只要函数 returns 为真值 1,过滤就会按预期工作。

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


1 引用自 Python's official documentation,

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

所以,只要你的函数 returns 除了上面列表中提到的虚假项目之外的任何东西,条件就会得到满足。


除此之外,Python 的列表理解语法允许您在其中包含多个 if 子句。比如你要找出30以内所有不是5的倍数的3的倍数,你可以这样写

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

效果相同
>>> [index for index in range(30) if index % 3 == 0 and index % 5 != 0]
[3, 6, 9, 12, 18, 21, 24, 27]