【问题标题】:Printing specific combinations打印特定组合
【发布时间】:2021-07-31 01:14:14
【问题描述】:

我一直在做一些组合程序,目前,我想做的是通过以下技术完成:

from itertools import combinations

item_1 = [1,2,3,4,5,6,8,7]
item_2 = [10,12,14,15,16,17,19]
item_3 = [21,22,23,27,25,29]
item_4 = [32,33,36,37,38,39]
item_5 = [42,43,45,46,47,49]
item_6 = [51,52,53,57,59]
item_7 = [61,62,68]
item_8 = [71,72,75,78,79]

all_lists = item_1 + item_2 + item_3 + item_4 + item_5 + item_6 + item_7 + item_8

for (a,b,c,d,e,f,g,h) in combinations(all_lists, 8):
    print((a,b,c,d,e,f,g,h))
OUTPUT:
(1, 2, 3, 22, 25, 32, 39, 45)
(1, 2, 3, 22, 25, 32, 39, 46)
(1, 2, 3, 22, 25, 32, 39, 47)
(1, 2, 3, 22, 25, 32, 39, 49)
(1, 2, 3, 22, 25, 32, 39, 51)
(1, 2, 3, 22, 25, 32, 39, 52)
(1, 2, 3, 22, 25, 32, 39, 53)
(1, 2, 3, 22, 25, 32, 39, 57)

但是,我不需要包含重叠的项目,例如:

item_1 = [1,2,3,4,5,6,8,7] should all stay in the 'a' variable
item_2 = [10,12,14,15,16,17,19] should all stay in the 'b' variable
item_3 = [21,22,23,27,25,29] should all stay in the 'c' variable

我只是想查看所有组合,但将每个列表保留在单独的字母中,但现在它正在检查所有列表的组合,因为我将它们加在一起以使 combinations() 函数起作用。

有没有办法或其他 itertools 函数来完成我想要实现的目标?

【问题讨论】:

  • 也许您想要列表的 product 而不是它们串联的组合?
  • 也许你想要“itertools.product(item_1, item_2,...)”?如果没有,请显示预期输出的示例。

标签: python combinations itertools


【解决方案1】:

我想你在关注product

from itertools import product

item_1 = [1,2,3,4,5,6,8,7]
item_2 = [10,12,14,15,16,17,19]
item_3 = [21,22,23,27,25,29]
item_4 = [32,33,36,37,38,39]
item_5 = [42,43,45,46,47,49]
item_6 = [51,52,53,57,59]
item_7 = [61,62,68]
item_8 = [71,72,75,78,79]

all_lists = [item_1, item_2, item_3, item_4, item_5, item_6, item_7, item_8]

for (a,b,c,d,e,f,g,h) in product(*all_lists):
    print((a,b,c,d,e,f,g,h))

【讨论】:

  • 是的,这正是我要找的,我知道那里必须有其他功能才能使用。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-10
  • 1970-01-01
  • 1970-01-01
  • 2020-10-23
  • 2020-06-10
相关资源
最近更新 更多