gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:00:59 26 4
gpt4 key购买 nike

我的代码是:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com