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

2024-04-27 02:37:09 发布

您现在位置:Python中文网/ 问答频道 /正文

列表理解中的筛选子句

作为一个特别有用的扩展,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)]

Tags: the函数in列表forindexreturnif
1条回答
网友
1楼 · 发布于 2024-04-27 02:37:09

是的,你完全可以加上这个。该构造看起来类似于正常的过滤条件

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

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

只要函数返回truthy值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.

因此,只要函数返回除上面列表中提到的falsy项以外的任何内容,就可以满足条件。你知道吗


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

>>> [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]

相关问题 更多 >