计算两个列表的所有产品组合的pythonic 方法是什么。因此,给定两个长度为 n 的列表,我想返回一个长度为 2^n 的列表,其中包含产品。
像 list(itertools.product(on,off)) 但结果应该使用所有四个元素,而不仅仅是组合对,例如:
[(1.05, 5.53), (1.05, 3.12), (1.05, 3.75), (1.05, 4.75), (1.5, 5.53), (1.5, 3.12), (1.5, 3.75), (1.5, 4.75), (2.1, 5.53), (2.1, 3.12), (2.1, 3.75), (2.1, 4.75), (1.7, 5.53), (1.7, 3.12), (1.7, 3.75), (1.7, 4.75)]
更像这样:
off = [5.53,3.12,3.75,4.75]
on = [1.05,1.5,2.1,1.7]
# calculate combinations
x = combinations(on,off)
# Where...
# x[0] = off[0] * off[1] * off[2] * off[3] i.e
# x[0] = 5.53 * 3.12 * 3.75 * 4.75
#
# x[1] = off[0] * off[1] * off[2] * on[3] i.e
# x[1] = 5.53 * 3.12 * 3.75 * 1.7
#
# x[2] = off[0] * off[1] * on[2] * on[3] i.e
# x[2] = 5.53 * 3.12 * 2.1 * 1.7
#
# ...
#
# x[15] = on[0] * on[1] * on[2] * on[3] i.e
# x[15] = 1.05 * 1.5 * 2.1 * 1.7
输出可以类似于 itertools.product() 方法即 [(5.53, 3.12, 3.75, 4.75),(5.53, 3.12, 3.75, 1.7), ...] 我需要计算乘积,但我对组合方法很感兴趣。
注意:当我说 pythonic 方式时,我指的是利用 python 结构、库的简单的一两行代码 (itertools ect)。
请您参考如下方法:
你们非常亲密,itertools.combinations() .
