python - 如何在Python中合并单个列表并求和?

标签 python regex list iterator

我的代码是:

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)函数等但无法解决。 我想要的就是将这些不同的列表合并到单个列表中并进行求和。任何帮助将不胜感激。

最佳答案

在开始循环之前保留一个运行总计,然后将每行的内容添加到该总计中:

total = 0
for line in test:
    convert = re.findall(r'[-+]?\d*\.\d+|\d+', line)
    result = map(int, convert)
    total += sum(result)

print total

关于python - 如何在Python中合并单个列表并求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35056787/

相关文章:

python - 在 PyDev 中,如何为方法返回的实例获取自动完成功能?

python - 可选位置参数的 Argparse 值

php - 具有负向后查找和未知中段 PHP 的正则表达式

c# - 按列表属性比较相等性

python - 无法在 Python OpenCV v4.20 中使用 SIFT

python - python 中的子进程无法正确显示 linux 脚本中的 read -p 命令

regex - 正则表达式匹配中的固定字符数

java - 使用正则表达式在字符串(a href)中查找片段

python - numpy 数组列表的形状

list - 使用 LISP 遍历列表中的每个项目