简体   繁体   中英

iterate one row at a time of a 2D numpy array python

I have array which looks like below.

[['dad', 'mom', 'test1.txt']
['brother', 'sister', 'test2.txt']
['uncle', 'aunty', 'test3.txt']
['grandpa', 'grandma', 'test4.txt']]

I want to iterate for example. I open test1.txt file from 1st first element and if the string 'dad' and 'mom' are present in splitted index then filter the file and read and append the ages. likewise for text2.txt file if 'brother' and 'sister' are present then read and filter and i want it in nested list only not in same.

i have something like below

lst_age=[]
for data in ele_arry:
    file = data[2]
    stg1 = data[1]
    stg2 = data[0]
    files = open(file, 'r').read()
    for line in files:
        formattedline = line.split(' ')
        if formattedline[1] == stg1 and formattedline[2] == stg2:
            lst_age.append(formattedline[3])

Text file looks like below after splitting line by line:

['1','dad', 'mom', '27']
['2','dad', 'mom', '34']
['3','daughter', 'mom', '42']
['4','dad', 'son', '21']
['5','daughter', 'son', '22']

the output i need is for lst_age variable

['27', '34'] #for file text1.txt
['28', '43' ] #for file text2.txt
#similarly for all the 4 files 

but now i'm getting combined elements of ages from all the files into one.

['27', '34','28', '43'] 

This is not giving required output at above mentioned. can someone please help me in this issue?

Thanks!

This happens because with files = open(file, 'r').read() you will get returned a file object and not an iterable list. You could use readlines() that returns a list with lines of the file:

ele_arry =[['dad', 'mom', 'C:\\Users\\Miguel\\Desktop\\test1.txt'],
['brother', 'sister', 'C:\\Users\\Miguel\\Desktop\\test2.txt'],
['uncle', 'aunty', 'C:\\Users\\Miguel\\Desktop\\test3.txt'],
['grandpa', 'grandma', 'C:\\Users\\Miguel\\Desktop\\test4.txt']]


lst_age=[]
for data in ele_arry:
    file = data[2]
    stg2 = data[1]
    stg1 = data[0]
    files = open(file, 'r').readlines()
    lst_agefile=[]
    for line in files:
        formattedline = line.split(' ')
        if formattedline[1] == stg1 and formattedline[2] == stg2:
            lst_agefile.append(formattedline[3].replace('\n',''))
    lst_age.append(lst_agefile)
for i in lst_age:
    print(i)

Output:

['27', '34'] 
['28', '43' ]

A one-line way:

lst_age=[[line.split(' ')[3].replace('\n','') for line in open(data[2], 'r').readlines() if line.split(' ')[1] == data[0] and line.split(' ')[2] ==  data[1]] for data in ele_arry]

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