基本上,我正在尝试使用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
仍在努力使此代码更简洁。
答案 0 :(得分:1)
也许:
print([x + y for x, y in zip(pos, neg)])
输出:
[[('a', 1), ('b', 1), ('c', -1), ('d', -1)], [('a', 1), ('b', 0.5), ('c', -1), ('d', -0.5)], [('a', 1), ('b', 0), ('c', -1), ('d', 0)], [('a', 0.5), ('b', 1), ('c', -0.5), ('d', -1)], [('a', 0.5), ('b', 0.5), ('c', -0.5), ('d', -0.5)], [('a', 0.5), ('b', 0), ('c', -0.5), ('d', 0)], [('a', 0), ('b', 1), ('c', 0), ('d', -1)], [('a', 0), ('b', 0.5), ('c', 0), ('d', -0.5)], [('a', 0), ('b', 0), ('c', 0), ('d', 0)]]