python - 为什么在 iterable 上调用 list() 会改变它?

标签 python iterator iterable

考虑这段代码,其中我使用组合并尝试从中创建一个列表。

from itertools import combinations

t = (1,2,3,4)
print("t is %r" % (t,))
print("list(t) is %r" % list(t))
print("list(t) is %r" % list(t))

t2 = ("a", "b", "c", "d")
print("t2 is %r" % (t2,))

combs = combinations(t2, 2)
print("List of combinations of t2: %r" % list(combs))
print("List of combinations of t2: %r" % list(combs))

输出是(对我来说出乎意料的)

t is (1, 2, 3, 4)
list(t) is [1, 2, 3, 4]
list(t) is [1, 2, 3, 4]
t2 is ('a', 'b', 'c', 'd')
List of combinations of t2: [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
List of combinations of t2: []

很明显,list() 有副作用。 正如预期的那样,将元组转换为列表不会更改原始数据,我可以多次执行。但是,当我对从组合返回的可迭代对象尝试相同的操作时,这只有效一次,然后该可迭代对象似乎无效。 list 是否在可迭代对象上调用 next ,以便在完成后,迭代器位于末尾,或者为什么会发生这种情况? 我怎样才能避免它?

最佳答案

itertools.combinations 生成一个惰性生成器,而不是保存在内存中的完整数据结构。一旦你用list()之类的东西耗尽它(迭代它),它就......好吧,耗尽了。空的。如果想重复使用,请保存引用:

combs = list(combinations(t2, 2))
print("List of combinations of t2: %r" % combs)
print("List of combinations of t2: %r" % combs)

关于python - 为什么在 iterable 上调用 list() 会改变它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36966038/

相关文章:

python - 为什么我不能用 np.zeros 初始化一个数组,然后将元素更改为数组?

c++ - 设置不插入

c++ - 遍历 C++ map<int, list<int>>

python - Python 中检查句子是否回文的更好方法

python - 从页面获取链接 - python

python - Pandas 数据框中等效的 SQL 查询

iterator - 在迭代另一个属性时修改结构的一个属性

Go:抽象可迭代

python - 在 Python 3 中获取第一项 `OrderedDict` 的最短方法

java - 将流变成可迭代?