【发布时间】:2019-06-19 09:39:58
【问题描述】:
基本上我正在尝试使用 itertools.product 减少组合的数量,但使用 2 个列表从 4 个元素中获取所有组合。
我能够创建 2 个单独的元素组合列表,但我不知道如何组合这 2 个列表以获得它们的所有组合。
import itertools
pos_vars = ('a', 'b')
pos_num = (1, 0.5, 0)
neg_vars = ('c', 'd')
neg_num = (-1, -0.5, 0)
pos = [list(zip(pos_vars, p)) for p in itertools.product(pos_num, repeat=2)]
print(pos)
[[('a', 1), ('b', 1)], [('a', 1), ('b', 0.5)], [('a', 1), ('b', 0)], [('a', 0.5), ('b', 1)], [('a', 0.5), ('b', 0.5)], [('a', 0.5), ('b', 0)], [('a', 0), ('b', 1)], [('a', 0), ('b', 0.5)], [('a', 0), ('b', 0)]]
neg = [list(zip(neg_vars, n)) for n in itertools.product(neg_num, repeat=2)]
print(neg)
[[('c', -1), ('d', -1)], [('c', -1), ('d', -0.5)], [('c', -1), ('d', 0)], [('c', -0.5), ('d', -1)], [('c', -0.5), ('d', -0.5)], [('c', -0.5), ('d', 0)], [('c', 0), ('d', -1)], [('c', 0), ('d', -0.5)], [('c', 0), ('d', 0)]]
两个列表的组合列表应如下所示:
[[('a', 1), ('b', 1), ('c', -1), ('d', -1)], [('a', 1), ('b', 1), ('c', -1), ('d', -0.5)], etc.]
我能够获得全部范围,但基本上将我试图避免使用以下代码的计算量加倍:
full_var = ('a', 'b', 'c', 'd')
full_num = (-1, -0.5, 0, 0.5, 1)
full = [list(zip(full_var, f)) for f in itertools.product(full_num, repeat=4)]
提前致谢!
更新 - 我获得了 81 种组合。不是最有效的编码,但它可以工作并且可以改进。
pos_a_var = ('a')
pos_b_var = ('b')
neg_c_var = ('c')
neg_d_var = ('d')
pos_num = (1, 0.5, 0)
neg_num = (-1, -0.5, 0)
pos_a = list(itertools.product(pos_a_var, pos_num))
pos_b = list(itertools.product(pos_b_var, pos_num))
neg_c = list(itertools.product(neg_c_var, neg_num))
neg_d = list(itertools.product(neg_d_var, neg_num))
comb_list = [pos_a, pos_b, neg_c, neg_d]
all_combinations = list(itertools.product(*comb_list))
len(all_combinations)
81
仍在努力使这段代码更简洁。
【问题讨论】:
-
您是否对这两种方法都进行了计时,看看其中一种方法是否比另一种更快/更慢?
-
但是你确定当你将 pos 和 neg 组合成你的最终输出时,你最终会得到或多或少相同数量的组合
-
我应该得到 3^4 = 81 个组合。完整是 5^4 = 625 个组合
标签: python combinations product itertools