1

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这样做的方式时,我的意思是利用 pythons 结构、库(itertools 等)的简单一两行代码。

4

3 回答 3

5

你非常接近,itertools.combinations().

于 2012-11-05T13:19:27.520 回答
2

您可以从 开始生成所有2**4可能性itertools.product([0, 1], 4)。这会枚举长度为 4 的0s 和1s 的所有可能序列,然后您可以将每个 0-1 序列转换为off和的值序列on,方法是取off[i]0-1 序列的第 i 个元素是否为0on[i]否则。在代码中:

>>> import itertools
>>> off = [5.53,3.12,3.75,4.75]
>>> on = [1.05,1.5,2.1,1.7]
>>> for choices in itertools.product([0, 1], repeat=len(off)):
...     print [(on[i] if choice else off[i]) for i, choice in enumerate(choices)]
... 
[5.53, 3.12, 3.75, 4.75]
[5.53, 3.12, 3.75, 1.7]
[5.53, 3.12, 2.1, 4.75]
[5.53, 3.12, 2.1, 1.7]
... <10 more entries omitted ...>
[1.05, 1.5, 2.1, 4.75]
[1.05, 1.5, 2.1, 1.7]

要打印产品而不是列表:

>>> import operator
>>> for choices in itertools.product([0, 1], repeat=len(off)):
...     elts = [(on[i] if choice else off[i]) for i, choice in enumerate(choices)]
...     print reduce(operator.mul, elts, 1)
... 
307.32975
109.9917
172.10466
61.595352
...

如果您有可用的 numpy 并且愿意使用 numpy 数组而不是 Python 列表,那么有一些不错的工具,如numpy.choose可用。例如:

>>> import numpy
>>> numpy.choose([0, 1, 0, 1], [off, on])
array([ 5.53,  1.5 ,  3.75,  1.7 ])
>>> numpy.product(numpy.choose([0, 1, 0, 1], [off, on]))
52.880624999999995

结合早期的解决方案给出:

>>> for c in itertools.product([0, 1], repeat=4):
...     print numpy.product(numpy.choose(c, [off, on]))
... 
307.32975
109.9917
172.10466
61.595352
147.7546875
52.880625
...
于 2012-11-05T13:36:40.783 回答
0

这是你想要的吗:

off = [5.53,3.12,3.75,4.75]
on = [1.05,1.5,2.1,1.7]
import itertools as it
import operator

indices = list(it.product([0,1],[0,1],[0,1],[0,1]))
off_on = off,on
a = [reduce(operator.mul,(off_on[z][i] for i,z in enumerate(x))) for x in indices]
print a


#Numpy solution
import numpy as np
indices = list(it.product([0,1],[0,1],[0,1],[0,1]))
off_on = off,on
b = np.array([off,on])
loff = range(len(off))
aa = [np.prod(b[list(x),loff]) for x in indices]

print aa
print aa == a
于 2012-11-05T13:24:32.240 回答