4

你如何确定python中数组中所有数字的乘积/和/差/除法?例如乘法:

array=[1,2,3,4]

输出将仅为 1*2、1*3、1*4、2*3、2*4、3*4:

[2,3,4,6,8,12] 

我了解“for”和“while”循环是如何工作的,但一直无法找出解决方案——如何在 len(array) 变量数组中找到每组唯一的 2 个变量?在我这样做之后,我可以做相应的乘法/除法/减法/等。

我最多只能做一个数组的乘积:

array=[1,2,3]
product = 1
for i in array:
    product *= i
print product
4

4 回答 4

8

使用itertools.combinations

>>> from itertools import combinations
>>> array = [1, 2, 3, 4]
>>> [i * j for i, j in combinations(array, 2)]
[2, 3, 4, 6, 8, 12]
于 2013-10-13T02:40:37.157 回答
6

干得好。当您知道技巧时,这很容易;-)

>>> from itertools import combinations
>>> [a*b for a, b in combinations([1,2,3,4], 2)]
[2, 3, 4, 6, 8, 12]
于 2013-10-13T02:40:39.460 回答
4
array = [1, 2, 3, 4]

如果您仍然对基于循环的解决方案感兴趣。

result = []
for i in range(len(array)):
    for j in range(i + 1, len(array)):
        result.append(array[i] * array[j])
print result

这可以用列表理解来写,像这样

print [array[i] * array[j] for i in range(len(array)) for j in range(i + 1, len(array))]
于 2013-10-13T02:46:28.073 回答
4

使用所有的 ITERTOOLS!

>>> from itertools import starmap, combinations as combos
>>> from operator import mul
>>> products = starmap(mul, combos([1,2,3,4], 2))
>>> list(products)
[2, 3, 4, 6, 8, 12]

好的,不是全部,而是 MOAR。

于 2013-10-13T02:48:30.147 回答