python怎么在for循环里设置多个条件-python – for循环中的复合条件

其他答案和评论提出了一些不错的想法,但我认为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()