查找由2个独特的数组元素(python)生成的所有产品

Noo*_*der 4 python arrays loops

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

array=[1,2,3,4]
Run Code Online (Sandbox Code Playgroud)

输出只有1*2,1*3,1*4,2*3,2*4,3*4:

[2,3,4,6,8,12] 
Run Code Online (Sandbox Code Playgroud)

我理解"for"和"while"循环是如何工作但却无法找出解决方案 - 如何在len(数组)变量数组中找到每个唯一的2个变量集?在我这样做后,我可以做相应的乘法/除法/减法/等.

我所能做的就是阵列的产物:

array=[1,2,3]
product = 1
for i in array:
    product *= i
print product
Run Code Online (Sandbox Code Playgroud)

Ter*_*ryA 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]
Run Code Online (Sandbox Code Playgroud)

  • @TimPeters Pfft.我有链接.菜鸟 :) (7认同)
  • 哈!我的线路短一线 - LOL ;-) (5认同)

Tim*_*ers 6

干得好.当你知道技巧时很容易;-)

>>> from itertools import combinations
>>> [a*b for a, b in combinations([1,2,3,4], 2)]
[2, 3, 4, 6, 8, 12]
Run Code Online (Sandbox Code Playgroud)

  • 可悲的是,找到所有产品*的答案不是`itertools.product`. (2认同)