用于条件求和的Python代码 [英] Python code for sum with condition

查看:444
本文介绍了用于条件求和的Python代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

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

正确的结果是1968年.

The right result is 1968.

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

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

推荐答案

列表中有一个重复的元素84,因此array.index不能按您预期的那样工作.另外,您的代码具有二次复杂度,这不是必需的.

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

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

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

这篇关于用于条件求和的Python代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆