多列表的每种可能组合

时间:2015-03-07 00:49:18

标签: python python-3.x iterator generator itertools

list_a = [("A","<",1), ("A","==",5)]
list_b = [("B","<",5), ("B","==",7), ("B",">=",8)]
list_c = [("C","<",10),("C","<=",6),("C",">",4),("C","<=",6)]

我想列出每个可能的组合,每个列表只允许一个约束。

我可以看到itertools.product有点接近我想要的东西,我知道我可以做类似的事情

new_list = []
for a in list_a:
  for b in list_b:
    for c in list_c
      new_list.append(list(itertools.combinations([a,b,c],2)))

n**3这里的[("A","<",1)] [("A","<",1),("B","<",5)] [("A","<",1),("B","==",7)] [("A","<",1),("B",">=",8)] [("A","<",1),("B",">=",8),("C","<",10)] 复杂性似乎是一个令人难以置信的糟糕解决方案,因为我希望最终使用大小为30+的9个列表(即list_c,list_d,list_e等等) 以下是一些可接受的可能输出:

{{1}}

基本上我理解当你有一组数字时使用itertools,例如itertools.product(('ABCD'),3)会给出AAA,AAB,AAC,AAD,BAA,BAB的输出, BAC等,但我似乎无法弄清楚如何使用stdlib将“每个列表唯一一个”约束应用到最大延伸而不会破解一些非常低效的解决方案。

1 个答案:

答案 0 :(得分:3)

怎么样:

import itertools

list_a = [("A","<",1), ("A","==",5)]
list_b = [("B","<",5), ("B","==",7), ("B",">=",8)]
list_c = [("C","<",10),("C","<=",6),("C",">",4),("C","<=",6)]

lists = [list_a, list_b, list_c]


for l in lists: l.insert(0, None)

for x in itertools.product(*lists):
    print list(filter(None, x))

对于这些列表,我得到60个元素,包括一个空元素。

作为参考,下面列出了示例元素的索引:

[("A","<",1)]                           # 20
[("A","<",1),("B","<",5)]               # 25
[("A","<",1),("B","==",7)]              # 30
[("A","<",1),("B",">=",8)]              # 35
[("A","<",1),("B",">=",8),("C","<",10)] # 36