python - 是否可以限制 Python 中条件列表理解的长度?

标签 python list-comprehension

我正在做一个条件列表理解,例如newlist = [x for x in list if x % 2 == 0] .我想将结果列表的长度限制为特定数字。
如果不首先理解整个列表然后对其进行切片,这可能吗?
我想象一些具有以下功能的东西:

limit = 10
newlist = []

for x in list:

    if len(newlist) > limit:
        break 

    if x % 2 == 0:
        newlist.append(x)
切片原始列表(例如 [x for x in list[:25] if x % 2 == 0] 是不可能的,因为在我的特定用例中,if 条件不会在任何可预测的时间间隔内返回 True
提前谢谢了。

最佳答案

请不要命名任何变量 list因为它隐藏了内置 list构造函数。我用过 li作为此处输入列表的替代品。

import itertools as it

gen = (x for x in li if x % 2 == 0)  # Lazy generator.
result = list(it.islice(gen, 25))

关于python - 是否可以限制 Python 中条件列表理解的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65656985/

相关文章:

python - 加快查找两个词典之间的匹配项 (Python)

python - 使用列表理解来解决 Collat​​z 猜想

php - 如果 EXIF 信息更新,则不会更改的唯一图像哈希

python - 适用于 python 的 Google Api 客户端库不会在文件 : list method with query 中返回 nextPageToken

python - 创建具有理解力的字典?

python - 将一本书解析成章节——Python

python - 在 Python 中使用 Selenium 查找登录按钮 id

python - 在不改变第一个列表的顺序的情况下找到两个列表的公共(public)元素的最快方法

python - 列表理解和就地方法

python解压列表字典