【问题标题】:Is there a way to break out of list comprehension?有没有办法打破列表理解?
【发布时间】:2016-11-19 19:31:36
【问题描述】:

在使用无限生成器时,我可以使用if 来阻止项目进入列表,但不是为了打破循环。

这实际上会崩溃并挂起。甚至KeyboardInterrupt 也救不了我(顺便说一句,为什么?)

import itertools
a = [x for x in itertools.count() if x<10]

如果我使用自己的无限生成器

def mygen():
    i=0
    while True:
        yield i
        i +=1

这将持续到KeyboardInterrupt

a = [x for x in mygen() if x<10]

现在,显然对于正确的for 循环,我们可以在满足条件时中断

a = []
for x in itertools.count():
    a.append(x)
    if x>9:
        break

所以我的问题是:有没有办法打破列表理解?

【问题讨论】:

  • 列表推导不是千里眼[x for x in itertools.count() if x&lt;10] 将尝试遍历 count 对象中的所有项目,并且只返回那些小于 10 的项目。它会一直持续下去。 . .

标签: python


【解决方案1】:

在不再满足条件后使用itertools.takewhile 停止迭代...:

import itertools

a = [x for x in itertools.takewhile(lambda L: L < 10, itertools.count())]
# a = list(itertools.takewhile(lambda L: < 10, itertools.count()))

本身并没有一种方法可以打破列表组合,因此限制可迭代(takewhileislice 等......是要走的路......)

【讨论】:

    猜你喜欢
    • 2017-04-26
    • 2019-04-24
    • 2011-06-04
    • 2017-01-28
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    • 2011-01-15
    相关资源
    最近更新 更多