我在 google colab notebook 中运行以下代码
from itertools import permutations
p = permutations([1, 2, 3])
print(list(p))
for i in list(p):
print(i)
在上面的代码中,首先 print(list(p))打印语句,但第二个print(i)没有显示任何结果。
任何人都可以知道发生这种情况的原因吗?
from itertools import permutations
p = permutations([1, 2, 3])
print(list(p))
for i in list(p):
print(i)
在上面的代码中,首先 print(list(p))打印语句,但第二个print(i)没有显示任何结果。
任何人都可以知道发生这种情况的原因吗?
p是一个迭代器。它只能食用一次。由于第一个list(p)已经消耗它,第二个list(p)将给出一个空列表。如果你需要多次使用它,你需要将它物化为一个列表:
p = list(permutations([1, 2, 3]))
print(p)
for i in p:
print(i)
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)