I've got a list of lists in Python 2.7 with numbers in strings:
[['1', '2'], ['3'], ['4', '5', '6']]
How could I sum all the numbers in these lists?
I've got a list of lists in Python 2.7 with numbers in strings:
[['1', '2'], ['3'], ['4', '5', '6']]
How could I sum all the numbers in these lists?
You have first chain
all the lists, then convert them to int
using map
and finally sum
them.
import itertools
m = [['1', '2'], ['3'], ['4', '5', '6']]
print sum(map(int, list(itertools.chain(*m))))
Output:
21
As an alternate solution to chaining them you could use list comprehension and convert each element to an int and then sum the new list
l = [['1', '2'], ['3'], ['4', '5', '6']]
print sum([int(j) for i in l for j in i])
21