how do i put my condition result into a list?

I want to open a file, get numbers after the = sign, and put the result into a list. I did the first steps, but I'm stuck with assignment of the results into a list.

I tried to create a list and assign the result on it but when I print my list it shows me only the last results:

import cv2 as cv
import time
import numpy
from math import log
import csv
import re

statList = []

with open("C:\\ProgramData\\OutilTestObjets3D\\MaquetteCB-2019\\DataSet\\DEFAULT\\terrain\\3DObjects\\building\\house01.ive.stat.txt", 'r') as f:
    #
    statList = f.readlines()
    statList = [x.strip() for x in statList]
    for line in statList :
        if (re.search("=" ,str(line))):
            if (re.search('#IND',str(line))):
                print("ERREUR")
            else:
                results = re.findall("=\s*?(\d+\.\d+|\d+)", str(line))
                print ("result="+str(results))
                statList.append(log(float(results[0])))

                floatList = [str(results)]
                print(floatList)

2 answers

  • answered 2019-07-18 16:13 Doug Moses

    Its because you are overwriting results variable each time through your loop. try

        #
    results = []
    statList = f.readlines()
    statList = [x.strip() for x in statList]
    for line in statList :
        if (re.search("=" ,str(line))):
            if (re.search('#IND',str(line))):
                print("ERREUR")
            else:
                results.extend(re.findall("=\s*?(\d+\.\d+|\d+)", str(line)))
                print ("result="+str(results))
                statList.append(log(float(results[0])))
    
                floatList = [str(results)]
                print(floatList)
    

  • answered 2019-07-18 16:14 Masoud

    The problem with your program is defining an empty list statList, then redefine it as statList = f.readlines() and append results to it. So, change the name of empty list, then you can use extend as long as results are list objects. And finally, use built-in map function to apply a function for every single item of your list:

    from math import log
    import re
    
    final_result = []
    with open("file.txt", 'r') as f:
        #
        statList = f.readlines()
        statList = [x.strip() for x in statList]
        for line in statList :
            if (re.search("=" ,str(line))):
                if (re.search('#IND',str(line))):
                    print("ERREUR")
                else:
                    result = re.findall("=\s*?(\d+\.\d+|\d+)", str(line))
                    print("result=" + result[0])
                    final_result.extend(result)
                    #  final_result.append(result[0])
    
    floats_list = list(map(float, final_result))
    logs_list = list(map(log, floats_list))