简体   繁体   中英

how to merge in single list and do sum in python?

my code is:

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    

i got console output as :

[]
[]
[]
[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]
[]

i tried using operator , reduce(lamda) function and so on but couldn't solve. All i want is to merge those different lists into single list and do sum. Any help would be appreciated.

You can simply do

result = sum(map(int, convert))  
total = result+total

total=0 should be out of loop .Take it before for line in

Keep a running total before you start the loop, then add each line's contents to that total:

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

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

map return a list, keep adding this list in result list, At last you will have result list with all required integer. Then sum it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM