我正在阅读我的一些旧代码并遇到了这一行
itertools.starmap(lambda x,y: x + (y,),
itertools.izip(itertools.repeat(some_tuple,
len(list_of_tuples)),
itertools.imap(lambda x: x[0],
list_of_tuples)))
需要明确的是,我有一些list_of_tuples
我想从中获取每个元组中的第一项( itertools.imap
),我有另一个要重复的元组( itertools.repeat
),这样 list_of_tuples
中的每个元组都有一个副本,然后我想根据 list_of_tuples
中的项目获取新的、更长的元组(itertools.starmap
)。
例如,假设 some_tuple = (1, 2, 3)
和list_of_tuples = [(1, other_info), (5, other), (8, 12)]
。我想要类似[(1, 2, 3, 1), (1, 2, 3, 5), (1, 2, 3, 8)]
的东西。这不是确切的 IO(它使用了一些非常不相关且复杂的类),而且我的实际列表和元组非常大。
像这样嵌套迭代器有什么意义吗?在我看来,itertools 中的每个函数都必须迭代我给它的迭代器,并将其中的信息存储在某个地方,这意味着将其他迭代器放在 starmap
中没有任何好处。 。我完全错了吗?这是如何工作的?
最佳答案
没有理由嵌套迭代器。使用变量不会对性能/内存产生明显影响:
first_items = itertools.imap(lambda x: x[0], list_of_tuples)
repeated_tuple = itertools.repeat(some_tuple, len(list_of_tuples))
items = itertools.izip(repeated_tuple, first_items)
result = itertools.starmap(lambda x,y: x + (y,), items)
itertools 使用和返回的迭代器对象并不将所有项存储在内存中,而只是在需要时计算下一项。您可以阅读有关它们如何工作的更多信息 here .
关于python - 使用嵌套迭代器有什么意义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26965747/