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

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

提交回复
热议问题