Reputation: 245
I'm looking for method in python to sum a list of list that contain only integers.
I saw that the method sum()
works only for list but not for list of list.
There is anything fit for me?
thank you
Upvotes: 2
Views: 12220
Reputation: 81
import re
print sum( [int(i) for i in re.findall('[0-9]+', open("regex_sum_301799.txt").read()) ] )
Example File Source: http://python-data.dr-chuck.net/regex_sum_301799.txt
Upvotes: 0
Reputation: 251186
You can use sum()
with a generator expression here:
In [18]: lis = [[1, 2], [3, 4], [5, 6]]
In [19]: sum(sum(x) for x in lis)
Out[19]: 21
or:
In [21]: sum(sum(lis, []))
Out[21]: 21
timeit
comparisons:
In [49]: %timeit sum(sum(x) for x in lis)
100000 loops, best of 3: 2.56 us per loop
In [50]: %timeit sum(map(sum, lis))
100000 loops, best of 3: 2.39 us per loop
In [51]: %timeit sum(sum(lis, []))
1000000 loops, best of 3: 2.21 us per loop
In [52]: %timeit sum(chain.from_iterable(lis)) # winner
100000 loops, best of 3: 1.43 us per loop
In [53]: %timeit sum(chain(*lis))
100000 loops, best of 3: 1.55 us per loop
Upvotes: 10
Reputation: 11
import re
#print sum( [ ****** *** * in **********('[0-9]+',**************************.read()) ] )
name = raw_input("Enter file:")
if len(name) < 1 : name = "sam.txt"
handle = open(name)
#handle = handle.read()
num = list()
total = 0
for line in handle:
line = line.rstrip()
if len(re.findall('([0-9]+)', line))== 0: continue
num.append(re.findall('([0-9]+)', line))
print sum(sum(num,[]))
Upvotes: 0
Reputation: 49886
import itertools
sum(itertools.chain.from_iterable([[1,2],[3,4],[5,6]]))
itertools.chain
flattens one level of iterable (which is all you need here), so sum
gets the list with the sublists broken out.
Upvotes: 5
Reputation: 5191
l = [[1,2,3], [3,4,5], [3,5,6]]
total = sum([sum(x) for x in l])
Upvotes: 1
Reputation: 25474
sum(map(sum, my_list))
This runs sum on every element of the first list, then puts the results from those into sum again.
Upvotes: 2