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-ideas和 its continuation是这个问题的最佳答案。
总而言之:这个想法在过去已经被讨论过,而且好处似乎不足以激发语法变化,考虑到:
增加语言的复杂性和对学习曲线的影响
所有实现的技术变化:CPython、Jython、Pypy..
极端使用 synthax 可能导致的奇怪情况
人们似乎高度重视的一点是避免带来损害可维护性的类似 Perl 的复杂性。
This message和 this 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/