如何限制理解力的大小?

如何限制理解力的大小?

问题描述:

我有一个list,想(通过理解)建立另一个列表.我希望通过条件限制此新列表的大小

I have a list and want to build (via a comprehension) another list. I would like this new list to be limited in size, via a condition

以下代码将失败:

a = [1, 2, 1, 2, 1, 2]
b = [i for i in a if i == 1 and len(b) < 3]

使用

Traceback (most recent call last):
  File "compr.py", line 2, in <module>
    b = [i for i in a if i == 1 and len(b) < 3]
  File "compr.py", line 2, in <listcomp>
    b = [i for i in a if i == 1 and len(b) < 3]
NameError: name 'b' is not defined

因为b在构建理解时尚未定义.

because b is not defined yet at the time the comprehension is built.

是否可以在构建时限制新列表的大小?

注意:到达计数器时,我可以使用正确的break将理解分解为for循环,但是我想知道是否存在使用理解的机制.

Note: I could break the comprehension into a for loop with the proper break when a counter is reached but I would like to know if there is a mechanism which uses a comprehension.

您可以使用生成器表达式进行过滤,然后使用islice()限制迭代次数:

You can use a generator expression to do the filtering, then use islice() to limit the number of iterations:

from itertools import islice

filtered = (i for i in a if i == 1)
b = list(islice(filtered, 3))

这确保您要做的工作不超过生产这三个元素所需的工作.

This ensures you don't do more work than you have to to produce those 3 elements.

请注意,这里不再使用列表理解了.列表理解无法打破,您被锁定到最后.

Note that there is no point anymore in using a list comprehension here; a list comprehension can't be broken out of, you are locked into iterating to the end.