[英]Python. How to sum up all even integers in a list?
I'm completely new to the subject and I want to ask how to sum up all even integers in a list (without using functions (I haven't studied them yet))?我对这个主题完全陌生,我想问一下如何总结列表中的所有偶数(不使用函数(我还没有研究过它们))? For example:例如:
myList = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]
I create for loop我创建 for 循环
for i in myList:
if x % 2 ==0:
# I'm stuck here
How to store these values to calculate the sum?如何存储这些值来计算总和?
Using a generator expression:使用生成器表达式:
>>> myList = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]
>>> sum(num for num in myList if not num%2)
60
Using filter()
:使用filter()
:
>>> myList = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]
>>> sum(filter(lambda x: not x%2, myList))
60
Using a manual loop:使用手动循环:
>>> 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
Sorry, I just had to golf this.对不起,我只是不得不打高尔夫球。 Maybe it'll teach someone the ~ operator .也许它会教某人~ 运算符。
>>> myList = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]
>>> sum(~i%2*i for i in myList)
60
Found another one with the same length:找到另一个长度相同的:
>>> sum(i&~i%-2for i in myList)
60
You need to store the result in a variable and add the even numbers to the variable, like so:您需要将结果存储在变量中并将偶数添加到变量中,如下所示:
>>> 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
>>>
You can filter out all non-even elements like so您可以像这样过滤掉所有非偶数元素
my_list = [1, 3, 5, 6, 8, 10, 34, 2, 0, 3]
even_list = filter(lambda x: x%2 == 0, my_list)
and then sum the output like so:然后像这样总结输出:
sum(even_list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.