0

基本上我试图减少使用 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

仍在努力使此代码更简洁。

4

1 回答 1

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)]]
于 2019-06-19T09:44:08.033 回答