复杂对象的python赋值

复杂对象的python赋值,python,Python,我有下面的代码,它工作得很好。但当我在语句printlist(B)中删除注释时,它失败并返回为空列表。我在想,也许X正在获取作为print语句的一部分执行的列表(B)的地址位置 import itertools A = [1,2,3] B = itertools.product(A,repeat=2) print str(B) #print list(B) X = list(B) print X <itertools.product object at 0x7f5ac40a9a50>

我有下面的代码,它工作得很好。但当我在语句print
list(B)
中删除注释时,它失败并返回为空列表。我在想,也许X正在获取作为print语句的一部分执行的
列表(B)
的地址位置

import itertools
A = [1,2,3]
B = itertools.product(A,repeat=2)
print str(B)
#print list(B)
X = list(B)
print X
<itertools.product object at 0x7f5ac40a9a50>
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
Command took 0.03s 
导入itertools
A=[1,2,3]
B=itertools.product(A,重复=2)
打印str(B)
#打印列表(B)
X=列表(B)
打印X
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
命令耗时0.03秒
B
是一个迭代器。如果您请求
list(B)
,那么您将耗尽迭代器,导致下次执行
list(B)
时迭代器为空

根据经验:在处理迭代器时,很少需要将它们指定给名称。通常,您可以使用
for in
对迭代器进行迭代,或者使用
list
将迭代器转换为一个列表。

返回一个迭代器,因此当您执行
打印列表(B)
时,它已经对所有产品进行了迭代,然后如果您重试
list(B)
,B将没有任何内容,因此
列表(B) 
将返回空列表

您只需尝试打印
list(B)
2次即可看到相同的结果-

>>> B = itertools.product(A,repeat=2)
>>> print list(B)
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
>>> print list(B)
[]

很高兴我能提供帮助。请记住通过点击答案左侧的勾号来接受答案(根据您的判断,这是最好的答案)。这将对社区有所帮助。