简体   繁体   中英

sum of even numbers in lists in list python

How do I find the even number from multiples of list and add them all together?
For example:
I have this function to start this

def sum_even_lol(lol):

and

sum_even_lol([[1,2,3],[6,5,4],[5,7,9]])

so it would be 2+6+4(calculation done by the code)
should return 12.

you can convert the list of lists to a flat list, then filter only the even numbers and add those in a generator expression like this:

def sum_even_lol(lol):
    return sum(n for l in lol for n in l if not n % 2)

or if you find nested generators less readable than ideal, you can reduce by using sum() - but you have to remember to provide an empty array as the initial value:

    return sum(n for n in sum(lol, []) if not n % 2)

You can find the evens by simple list comprehension :

evens = [item for i in lol for item in i if item%2==0]

The to return sum :

return sum(evens)

In all, the function definition would look something like this:

def sum_even_lol (lol):
    evens = [item for i in lol for item in i if item%2==0]
    return sum(evens)

您可以使用此:

sum(val for v in l for val in v if val % 2 == 0)

I'm a little bit unclear on what you're asking exactly, but these ideas might help.

Something like:

evens = [element for element in my_list if element%2 == 0]

will return a list, evens , that has only the even elements from the list my_list .

You can also use

list_sum = sum([my_list])

to easily get the sum of numbers in a list. I think you should be able to combine these together to do what you want from here!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM