-4

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?

Remi Guan
  • 21,506
  • 17
  • 64
  • 87

2 Answers2

3

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
Avión
  • 7,963
  • 11
  • 64
  • 105
3

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
SirParselot
  • 2,640
  • 2
  • 20
  • 31