【问题标题】:sum of elements but skip one element in each iteration in python元素的总和,但在 python 的每次迭代中跳过一个元素
【发布时间】:2020-01-09 20:24:46
【问题描述】:

在每次迭代中跳过数组的一个元素,同时在 python 中对数组求和,例如,如果我有一个数组 [0,2,3,5,6,5,8,9] 我如何对前 7 个元素求和,然后在下一次迭代中对其余数组求和,除了第一个元素

for x in range(len(arr)):
   maxi = max(sum(arr), maximum)

   return maxi

这返回整个数组的总和,但我想在每次迭代中跳过一个元素,然后跳过另一个元素,但添加前一个被跳过的元素

【问题讨论】:

    标签: python-3.x list


    【解决方案1】:

    对数组求和一次,然后一次减去一个元素:

    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))
    

    【讨论】:

    • 如果我想取这个数组的最大总和怎么办?我应该尝试最大功能吗?我试过但没有用,但感谢这段代码
    • @AbdulBasitNiazi 您可以将所有总和存储在一个列表中,然后使用max 函数或随时查找最大总和
    • 非常感谢@Deepspace
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 2018-01-01
    • 1970-01-01
    • 2014-03-12
    • 2011-08-15
    • 2020-12-05
    • 1970-01-01
    相关资源
    最近更新 更多