gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:56:30 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com