蟒蛇。如何总结列表中的所有偶数?

时间:2015-05-19 00:34:02

标签: python

我对这个主题完全陌生,我想问一下如何在列表中总结所有甚至整数(不使用函数(我还没有研究它们))? 例如:

myList = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]

我创建了for循环

for i in myList:
  if x % 2 ==0:
  # I'm stuck here

如何存储这些值以计算总和?

4 个答案:

答案 0 :(得分:7)

使用生成器表达式:

>>> myList = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]
>>> sum(num for num in myList if not num%2)
60

使用filter()

>>> myList = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]
>>> sum(filter(lambda x: not x%2, myList))
60

使用手动循环:

>>> myList = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]
>>> result = 0
>>> for item in myList:
...     if not item%2:
...             result += item
...
>>> result
60

答案 1 :(得分:5)

抱歉,我只是打高尔夫了。也许它会教别人the ~ operator

>>> myList = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]
>>> sum(~i%2*i for i in myList)
60

找到另一个长度相同的人:

>>> sum(i&~i%-2for i in myList)
60

答案 2 :(得分:1)

您需要将结果存储在变量中,并将偶数添加到变量中,如下所示:

>>> myList = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]
>>> result = 0  # Initialize your results variable.
>>> for i in myList:  # Loop through each element of the list.
...   if not i % 2:  # Test for even numbers.
...     result += i
... 
>>> print(result)
60
>>> 

答案 3 :(得分:1)

您可以过滤掉所有非偶数元素

my_list = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]
even_list = filter(lambda x: x%2 == 0, my_list)

然后对输出求和:

sum(even_list)