python - for 循环中的复合条件

标签 python for-loop syntax generator list-comprehension

Python 允许在列表理解中使用“if”条件,例如:

[l for l in lines if l.startswith('example')]

常规“for”循环中缺少此功能,因此缺少:

for line in lines if line.startswith('example'):
    statements

需要评估循环中的条件:

for line in lines:
    if line.startswith('example'):
        statements

或嵌入生成器表达式,如:

for line in [l for l in lines if l.startswith('example')]:
    statements

我的理解对吗?有没有比我上面列出的方法更好或更 pythonic 的方法来实现在 for 循环中添加条件的相同结果?

请注意,选择“lines”只是作为示例,任何集合或生成器都可以存在。

最佳答案

一些不错的想法来自其他答案和评论,但我认为 this recent discussion on Python-ideasits continuation是这个问题的最佳答案。

总而言之:这个想法在过去已经被讨论过,而且好处似乎不足以激发语法变化,考虑到:

  • 增加语言的复杂性和对学习曲线的影响

  • 所有实现的技术变化:CPython、Jython、Pypy..

  • 极端使用 synthax 可能导致的奇怪情况

人们似乎高度重视的一点是避免带来损害可维护性的类似 Perl 的复杂性。

This messagethis one很好地总结了 for 循环中复合 if 语句的可能替代方案(几乎也已经出现在本页中):

# nested if
for l in lines:
    if l.startswith('example'):
        body

# continue, to put an accent on exceptional case
for l in lines:
    if not l.startswith('example'):
        continue
    body

# hacky way of generator expression
# (better than comprehension as does not store a list)
for l in (l for l in lines if l.startswith('example')):
    body()

# and its named version
def gen(lines):
    return (l for l in lines if l.startswith('example'))
for line in gen(lines):
    body

# functional style
for line in filter(lambda l: l.startswith('example'), lines):
    body()

关于python - for 循环中的复合条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40593245/

相关文章:

python - 如果 PyPI 存在依赖关系,Pip 会忽略从 wheel 安装包的 dependency_links

c# - 如何循环所有功能?

java - 嵌套循环将数据添加到数组

syntax - 如何在 rdf :Seq? 中定义元素的类型

Haskell 保护 lambda 函数?

python - Imgur API 不改变现有图像的描述

Python Timedelta 算术与 noleap 日历

Python 将 JSON 转换为 CSV

python - 如何在 for 循环中创建和填充列表列表

sql - 嵌套,分组Sqlite语法?