【问题标题】:Why combinations object lose its content after using list?为什么组合对象在使用列表后会丢失其内容?
【发布时间】:2018-12-27 18:57:42
【问题描述】:

这可能很简单,但我卡了很长时间。

我试图迭代两种组合。但它并没有遍历所有项目。

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的第一个组合?

【问题讨论】:

标签: python-2.7 iterator


【解决方案1】:

我认为原因是在内部循环内部它以某种方式失去了 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')

【讨论】:

  • 这是有道理的。事实上,我做了同样的事情来解决这个问题。但我只是试图理解为什么会这样。
猜你喜欢
  • 2021-09-16
  • 2012-10-07
  • 2017-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
相关资源
最近更新 更多