为什么组合对象在使用列表后会丢失其内容?

时间:2018-12-27 18:57:43

标签: python-2.7 iterator

这可能很简单,但是我被困了很长时间。

我正在尝试迭代两个组合。但这并没有涉及所有项目。

itt_1 = [1, 2, 3] 
comb_1 = combinations(itt, 2)
itt_2 = ['a', 'b', 'c']
comb_2 = combinations(itt_2, 2)
count = 0
for ii in list(comb_1):
    for jj in list(comb_2):
        print ii, jj

我希望看到9个打印输出结果。但是,无论我是否使用列表函数,它仅显示其中的前3个,如下所示:

(1, 2) ('a', 'b')
(1, 2) ('a', 'c')
(1, 2) ('b', 'c')

我认为与组合有关,因为它是用于迭代的生成器,并且只能使用一次。这是否意味着它不能在嵌套for循环中使用?为什么在上面的示例中它只打印comb_1的第一个组合?

1 个答案:

答案 0 :(得分:0)

我认为原因是在内部循环内它以某种方式失去了comb_2的轨迹: 运行此:

itt_1 = [1, 2, 3] 
comb_1 = combinations(itt_1, 2)
itt_2 = ['a', 'b', 'c']
comb_2 = combinations(itt_2, 2)
count = 0
for ii in list(comb_1):
    print ii
    for jj in list(comb_2):
        print ii, jj

您将获得以下预测相同的结果:

(1, 2)
(1, 2) ('a', 'b')
(1, 2) ('a', 'c')
(1, 2) ('b', 'c')
(1, 3)
(2, 3)

尝试事先将它们转换为列表。 这对我有用:

itt_1 = [1, 2, 3]
comb_1 = list(combinations(itt_1, 2))
itt_2 = ['a', 'b', 'c']
comb_2 = list(combinations(itt_2, 2))
for ii in comb_1:
    for jj in comb_2:
        print ii, jj

结果:

(1, 2) ('a', 'b')
(1, 2) ('a', 'c')
(1, 2) ('b', 'c')
(1, 3) ('a', 'b')
(1, 3) ('a', 'c')
(1, 3) ('b', 'c')
(2, 3) ('a', 'b')
(2, 3) ('a', 'c')
(2, 3) ('b', 'c')