对数组求和一次,然后一次减去一个元素:
li = [0, 2, 3, 5, 6, 5, 8, 9]
array_sum = sum(li)
for n in li:
print('sum of array is', array_sum, ', without', n, 'the sum is', array_sum - n)
输出
sum of array is 38 , without 0 the sum is 38
sum of array is 38 , without 2 the sum is 36
sum of array is 38 , without 3 the sum is 35
sum of array is 38 , without 5 the sum is 33
sum of array is 38 , without 6 the sum is 32
sum of array is 38 , without 5 the sum is 33
sum of array is 38 , without 8 the sum is 30
sum of array is 38 , without 9 the sum is 29
如果您只对最大金额感兴趣:
li = [0, 2, 3, 5, 6, 5, 8, 9]
print(max(sum(li) - n for n in li))
此时,您甚至不需要循环。根据定义,我们将在对最小元素进行子结构时得到最大和。
print(sum(li) - min(li))