我正在寻找python中的方法来对仅包含整数的列表列表求和。我看到该方法sum()
仅适用于列表,但不适用于列表列表。有什么适合我的吗?
谢谢你
您可以sum()
在此处使用生成器表达式:
In [18]: lis = [[1, 2], [3, 4], [5, 6]]
In [19]: sum(sum(x) for x in lis)
Out[19]: 21
或者:
In [21]: sum(sum(lis, []))
Out[21]: 21
timeit
比较:
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
import itertools
sum(itertools.chain.from_iterable([[1,2],[3,4],[5,6]]))
itertools.chain
展平一级可迭代(这是您在这里所需要的),因此sum
获取包含子列表的列表。
sum(map(sum, my_list))
这将对第一个列表的每个元素运行 sum,然后将结果再次放入 sum 中。
l = [[1,2,3], [3,4,5], [3,5,6]]
total = sum([sum(x) for x in l])
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,[]))
import re
print sum( [int(i) for i in re.findall('[0-9]+', open("regex_sum_301799.txt").read()) ] )
示例文件来源: http: //python-data.dr-chuck.net/regex_sum_301799.txt