Python总结了一组数组

时间:2018-03-20 09:13:30

标签: python arrays list numpy sum

生成数组输出所需的任务目标,output[i]等于除nums[i]之外的所有nums元素的总和。

例如:给定[6,7,8,9],返回[24,23,22,21]

Input = [6,7,8,9]

背后的计算是

0+7+8+9 = 24
6+0+8+9 = 23
6+7+0+9 = 22
6+7+8+0 = 21

Output = [ 24, 24, 22, 21 ]

3 个答案:

答案 0 :(得分:2)

您可以使用列表理解:

In [1]: a = [6,7,8,9]

In [2]: s = sum(a)

In [3]: [s - i for i in a]
Out[3]: [24, 23, 22, 21]

答案 1 :(得分:1)

使用numpy广播+向量化操作:

import numpy as np

x = np.array([6,7,8,9])

y = np.sum(x) - x

# array([24, 23, 22, 21])

答案 2 :(得分:0)

您可以使用for循环和python的内置和函数

 a = [6,7,8,9] #your input array
 b = [] # initialise an empty list
 for index in range(len(a)): #iterate through the list's length
     b.append( sum( a[0:index] + a[index+1:] ) ) #add to two parts before and 
     # after the index
 print(b)