我的代码是:
import sys
import re
from timeit import itertools
import operator
fileName = 'realfile.txt'
test = open(fileName)
for line in test:
total =0
convert = re.findall(r'[-+]?\d*\.\d+|\d+', line)
result = map(int, convert)
total = result
print total
我的控制台输出为:
[]
[]
[]
[7152, 9977, 6801]
[]
[]
[4165]
[]
[]
[]
[]
[8572]
[9429, 4419, 3575]
[8032, 8040, 724]
[]
[5666, 7060, 807]
[]
[]
[]
[]
[]
[]
[]
[1812]
[]
[]
[]
[]
[3512, 6831]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[472, 660, 5749]
[9413]
[]
[]
[]
[]
[]
[]
[]
[4558]
[]
[]
[]
[1666, 7515, 1508]
[]
[2631, 3176]
[]
[]
[]
[]
[]
[]
[2439, 566, 1058]
[4406, 263, 3856]
[]
[]
[]
[]
[]
[]
[]
[4192, 6521]
[]
[]
[]
[]
[]
[7264, 4196]
[8948]
[]
[]
[]
[]
[]
[4714, 6691, 6965]
[]
[]
[]
[7404, 1430]
[]
[]
[]
[]
[]
[]
[]
[7259, 7475, 8892]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[7204]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[200, 5764]
[]
[]
[]
[]
[]
[]
[7160]
[]
[]
[]
[]
[]
[7209, 2247, 6555]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[393]
[]
[]
[]
[]
[]
[989, 8378]
[]
[]
[]
[4524, 1477]
[]
[]
[]
[]
[]
[2689, 5418, 8761]
[]
[]
[]
[]
[]
[1326]
[]
[]
[9050, 2979]
[]
[]
[]
[]
[1236]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[7009, 5660, 8064]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[9077, 4985, 5835]
[6548, 9909]
[]
[]
[]
[]
[4742, 7424, 7307]
[]
[]
[]
[]
[]
[6353]
[]
[]
[2123]
[]
[1311, 7273]
[]
[]
[]
[8933]
[]
[]
[]
[42]
[]
我尝试使用operator,reduce(lamda)等功能但无法解决。 我想要的只是将这些不同的列表合并到单个列表中并进行求和。任何帮助将不胜感激。
答案 0 :(得分:1)
你可以简单地做
result = sum(map(int, convert))
total = result+total
total=0
应该在loop
之外。在for line in
之前接受
答案 1 :(得分:1)
在开始循环之前保持运行总计,然后将每行的内容添加到该总计中:
total = 0
for line in test:
convert = re.findall(r'[-+]?\d*\.\d+|\d+', line)
result = map(int, convert)
total += sum(result)
print total
答案 2 :(得分:1)
result = []
for line in test:
convert = re.findall(r'[-+]?\d*\.\d+|\d+', line)
result = result + map(int, convert)
print result
print sum(result)
map返回一个列表,继续在结果列表中添加该列表,最后你将得到包含所有必需整数的结果列表。总结一下。