您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – for循环中的复合条件

5b51 2022/1/14 8:21:56 python 字数 2815 阅读 524 来源 www.jb51.cc/python

Python允许列表推导中的“if”条件,例如:[l for l in lines if l.startswith('example')] 常规“for”循环中缺少此功能,因此在没有:for line in lines if line.startswith('example'): statements 一个人需要评估循环中的条件:for line i

概述

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循环中添加条件的相同结果?

请注意选择“行”作为示例,任何集合或生成器都可以在那里.

总结一下:这个想法在过去已经讨论过了,考虑到以下因素,这些好处似乎不足以激发语法变化:

>语言复杂性增加,对学习曲线的影响
>所有实施中的技术变化: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循环中的复合条件全部内容,希望文章能够帮你解决python – for循环中的复合条件所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶