python - 使用嵌套迭代器有什么意义吗?

标签 python performance iterator python-itertools

我正在阅读我的一些旧代码并遇到了这一行

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/

相关文章:

python - 如何将 django 中的自定义 ID 字段重命名为默认值

python - 更改文件夹、所有子文件夹和所有文件的权限

performance - Sitecore - 负载平衡 Lucene 查询

performance - Pandas 或 scipy : looking for performance 中的 groupby.sum() 稀疏矩阵

Java迭代器

python - 在 Python 类中多次使用 super()

python - 使用python删除docker容器中的文件夹

php - 连接和搜索具有一对多关系的多个 MySQL 表

c++ - 是否有与基于范围的 for 循环兼容的 c.ended(iter) 方法?

c++ - 意外的 max_element 行为