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

自作多情 提交于 2021-01-27 22:40:27

问题


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 = 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. Can anyone point me in the right direction?


回答1:


You can filter out odd-values:

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


来源:https://stackoverflow.com/questions/42213455/using-sum-to-print-the-sum-of-even-numbers-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!