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

前端 未结 4 2079
一向
一向 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:01

    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
    >>> 
    
    0 讨论(0)
  • 2021-01-07 05:08

    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():

    >>> 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
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-07 05:18

    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)
    
    0 讨论(0)
提交回复
热议问题