简体   繁体   English

使用sum()打印列表中的偶数和

[英]Using sum() to print the sum of even numbers in a list

I am having trouble finding information on using sum to take from a list. 我在查找有关使用总和的信息时遇到困难。 I know how to use sum with range, for example: 我知道如何在范围内使用sum,例如:

sum = 0
for i in range(50):
    sum=sum + i
print (sum)

But I can't get my code to work when I am using a list such as [1, 2, 6, 7, 8, 10] and taking the even numbers using sum . 但是,当我使用诸如[1, 2, 6, 7, 8, 10]并使用sum取得偶数时,我的代码无法工作。 Can anyone point me in the right direction? 谁能指出我正确的方向?

You can filter out odd-values: 您可以filter出奇数值:

def is_even(x):
    # if the remainder (modulo) is 0 then it's evenly divisible by 2 => even
    return x % 2 == 0  

def sum_of_evens(it):
    return sum(filter(is_even, it))

>>> sum_of_evens([1,2,3,4,5])
6

Or if you prefer a conditional generator expression: 或者,如果您希望使用条件生成器表达式:

>>> lst = [1,2,3,4,5]
>>> sum(item for item in lst if item % 2 == 0)
6

Or the explicit (long) approach: 或显式(长)方法:

lst = [1,2,3,4,5]
sum_ = 0
for item in lst:
    if item % 2 == 0:
        sum_ += item
print(sum_)   # 6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM