多列表的所有可能组合
Every possible combination of a multi-list
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
复杂性似乎是一个非常糟糕的解决方案,因为我希望最终使用 9 个列表(即 list_c、list_d、list_e, 等...) 尺寸 30+
以下是一些可接受的可能输出:
[("A","<",1)]
[("A","<",1),("B","<",5)]
[("A","<",1),("B","==",7)]
[("A","<",1),("B",">=",8)]
[("A","<",1),("B",">=",8),("C","<",10)]
基本上我理解当你有一组 select 数字时 itertools 的用法,例如 itertools.product(('ABCD'),3) 会给出 AAA 的输出, AAB、AAC、AAD、BAA、BAB、BAC 等,但我似乎无法弄清楚如何使用 stdlib 将 "only one per list" 约束应用到最大扩展而不破解一些非常低效的解决方案。
怎么样:
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
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
复杂性似乎是一个非常糟糕的解决方案,因为我希望最终使用 9 个列表(即 list_c、list_d、list_e, 等...) 尺寸 30+
以下是一些可接受的可能输出:
[("A","<",1)]
[("A","<",1),("B","<",5)]
[("A","<",1),("B","==",7)]
[("A","<",1),("B",">=",8)]
[("A","<",1),("B",">=",8),("C","<",10)]
基本上我理解当你有一组 select 数字时 itertools 的用法,例如 itertools.product(('ABCD'),3) 会给出 AAA 的输出, AAB、AAC、AAD、BAA、BAB、BAC 等,但我似乎无法弄清楚如何使用 stdlib 将 "only one per list" 约束应用到最大扩展而不破解一些非常低效的解决方案。
怎么样:
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