加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – for循环中的复合条件

发布时间:2020-12-16 22:46:21 所属栏目:Python 来源:网络整理
导读: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 l

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读