带条件求和的 Python 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22895791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:54:52  来源:igfitidea点击:

Python code for sum with condition

pythonlistsumconditional-statementsslice

提问by beistvan

The task is following: sum the list elements with even indexes and multiply the result by the last list's elemet. I have this oneliner solution code in Python.

任务如下:对具有偶数索引的列表元素求和,并将结果乘以最后一个列表的元素。我在 Python 中有这个 oneliner 解决方案代码。

array = [-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41] 
print sum(i for i in array if array.index(i) % 2 == 0)*array[-1] if array != [] else 0

My result is -1476 ( The calculation is: 41*(-37-19+29+3-64+36+26+55+84-65) )

我的结果是-1476(计算是:41*(-37-19+29+3-64+36+26+55+84-65))

The right result is 1968.

正确的结果是 1968 年。

I can't figure it out why this code is not working correctly in this particular case.

我无法弄清楚为什么此代码在这种特殊情况下无法正常工作。

采纳答案by YS-L

There is a repeated element 84in the list, thus array.indexdoes not work as you expected it to be. Also, your code has a quadratic complexity which is not required.

列表中有一个重复的元素84,因此array.index不会像您预期的那样工作。此外,您的代码具有不需要的二次复杂度。

To fix your code with a minimum amount of edit, it would look something like this:

要以最少的编辑量修复您的代码,它看起来像这样:

array = [-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41] 
print sum(array[i] for i in range(len(array)) if i % 2 == 0)*array[-1] if array != [] else 0

回答by shaktimaan

This is what you are looking for:

这就是你要找的:

array[-1] * sum(array[::2])

array[::2]traverses the array from first index to last index in steps of two, i.e., every alternate number. sum(array[::2])gets the sum of alternate numbers from the original list.

array[::2]从第一个索引到最后一个索引以两步(即每个备用数)遍历数组。sum(array[::2])从原始列表中获取备用数字的总和。

Using indexwill work as expected only when you are sure the list does not have duplicates, which is why your code fails to give the correct result.

index只有当您确定列表没有重复项时,使用才会按预期工作,这就是您的代码无法给出正确结果的原因。

回答by vaultah

>>> sum(x for i, x in enumerate(array) if not i % 2)*array[-1] 
1968

Use the built-in enumeratefunction, since there're duplicate elements in your list, and list.index(x)returns the index of the firstelement equal to x(as said in the documentation). Also take a look at the documentation on enumerate.

使用内置enumerate函数,因为列表中有重复元素,并list.index(x)返回第一个元素的索引等于x(如文档所述)。另请查看有关enumerate.