Python. How to sum up all even integers in a list?

前端 未结 4 2096
一向
一向 2021-01-07 04:45

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:

4条回答
  •  粉色の甜心
    2021-01-07 05:11

    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
    

提交回复
热议问题