简体   繁体   English

存储大列表的前X个项目(Python)

[英]Storing First X Items of a Large List (Python)

Let's say we generate a large list of lists in Python using the combinations iterable, and you wanted to retrieve a list with certain properties. 假设我们使用可迭代的组合在Python中生成了大量列表,而您想检索具有某些属性的列表。

If the list of lists is sufficiently large, merely generating the list will take the bulk of the calculation time. 如果列表列表足够大,则仅生成列表将占用大量的计算时间。

Is there any way of generating the first x members of the iterable to reduce the overall calculation time? 有什么方法可以生成迭代器的前x个成员,以减少总体计算时间? Let's say: 比方说:

y=50
z=[list(combo) for combo in combinations(range(y + 1), 11)]

Let's say we have a function A, such that when we apply A to z, we get the required lists quickly. 假设我们有一个函数A,这样当我们将A应用于z时,我们会快速获得所需的列表。 Is there a method for applying the function A after each member of z is calculated? 在计算z的每个成员之后,是否有应用函数A的方法? So instead of calculating the entire list of lists first, the instant a single item is created, the function evaluates it? 因此,不是先计算列表的整个列表,而是在创建单个项目后立即对函数求值?

More generally, is there any method for retrieving the first x members of z, and not the entire list of lists? 更一般而言,是否有任何方法可以检索z的前x个成员,而不是整个列表?

Yup, use itertools.islice to limit the number. 是的,请使用itertools.islice限制数量。

from itertools import islice

combos = combinations(range(y + 1), 11)
data = [list(combo) for combo in islice(combos, 100)]

To take the first 100 from the combinations of combos... You can then keep consuming from combos afterwards... 要从连击组合中获取前100个...之后,您可以继续从combos消费...

print next(combos) # next combination
print list(islice(combos, 3, 13)) # skip 3 and take another 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM