是否可以在 Python 中限制条件列表理解的长度?
Is it possible to limit the length of a conditional list comprehension in Python?
我正在做条件列表理解,例如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 条件在任何可预测的时间间隔内都不 return 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))
由于您正在使用列表理解创建列表,因此您可以在创建列表后直接对其进行切片。
[x for x in list[:25] if x % 2 == 0][:limit]
我正在做条件列表理解,例如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 条件在任何可预测的时间间隔内都不 return 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))
由于您正在使用列表理解创建列表,因此您可以在创建列表后直接对其进行切片。
[x for x in list[:25] if x % 2 == 0][:limit]