Kebur Fantahun
Kebur Fantahun

Reputation: 93

How can I combine the elements of mulitple lists in python?

Here is the code to start off with.

#!/usr/bin/python

import glob
import re

path = '/home/lhco/f1/*.cut'

files=glob.glob(path)

i=0
for i in range(len(files)):
    x = files[i]
    h = x
    i += 1
    f = open(h)
    for line in f:
            x = re.findall("([0-9\.[0-9][e][+-][0-9]+)",line)
            pb = map(float, x)

            if "ESC_00" in line: print pb

Right now, the output is 3 lists of numbers from 3 files in the directory. What I want to do is try to take each first element, second etc. from the first list and add it to the next lists' first element, second, etc. I tried to use map again on "pb" and the sum and zip but that did not seem to help much. The initial output looks like:

[0.08]
[0.009]
[0.0]
[0.0]
[0.0]
[0.0]
[0.03]
[0.005]
[0.0]
[0.0]
[0.0]
[0.0]
[0.08]
[0.008]
[0.0]
[0.0]
[0.0]
[0.0]

Is it possible to add the first elements of all the sets of 6 numbers to each other? Do I need to try something with tuple here?

File example:

0 EVENTS SURVIVE AUXILIARY CUTS WITH 0.000e+00 PB RESIDUAL CROSS SECTION

EVENT SELECTION EFFICIENCY IS 100.000 PERCENT

CUT_KEY SURVIVE PB_AREA %_LOCAL %_TALLY
ESC_001      38 2.3e-02 007.317 007.317
ESC_002       9 5.5e-03 076.316 078.049
ESC_003       0 0.0e+00 100.000 100.000
ESC_004       0 0.0e+00 000.000 100.000
ESC_005       0 0.0e+00 000.000 100.000
ESC_006       0 0.0e+00 000.000 100.000

Upvotes: 0

Views: 72

Answers (1)

TemporalWolf
TemporalWolf

Reputation: 7952

results = []
for filename in files:
    with open(filename, 'r') as file:
        result = []
        for line in file:
            match = map(float, re.findall("([0-9\.[0-9][e][+-][0-9]+)", line))
            result.extend(match)
    results.append(result)
answer = zip(*results)

This builds result lists for each file, and a results list of lists, then zips them to form the answer, which is a list of tuples:

>>> zip(*results)
[(0.08, 0.03, 0.08), 
 (0.009, 0.005, 0.008), 
 (0.0, 0.0, 0.0), 
 (0.0, 0.0, 0.0), 
 (0.0, 0.0, 0.0), 
 (0.0, 0.0, 0.0)]

Additionally, there is a typo in your regex (see regex101):

([0-9\.[0-9][e][+-][0-9]+) Parses to

( [0-9\.[0-9] [e] [+-] [0-9]+ )

when I think you wanted:

( [0-9] \. [0-9] [e] [+-] [0-9]+ )

which can be simplified to (regex101):

\d\.\de[+-]\d+

Upvotes: 1

Related Questions