2个列表的Python组合

时间:2012-11-05 13:16:43

标签: python optimization performance

计算两个列表的所有产品组合的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这样做的方式我指的是利用蟒蛇结构的简单的一两行,库(itertools等)

3 个答案:

答案 0 :(得分:5)

你非常亲密,itertools.combinations()

答案 1 :(得分:2)

您可以从2**4开始生成所有itertools.product([0, 1], 4)种可能性。这列举了长度为4的01的所有可能序列,然后您可以将每个0-1序列转换为offon的值序列,如果0-1序列的第i个元素为off[i],则取0,否则为on[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
...

答案 2 :(得分: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
相关问题