nana
nana

Reputation: 17

Select the first element of a line with python

I'm having some problems in selecting the first element of a line with python. I have a txt file where the data are organized in this way:

0  3  546
1  2  435
2  4  900
22 3  384

I would like to print the lines whose first member matches with that of a list:

myList = [1, 22]

I've tried to do in this way:

for i in externalFile: 
   if i[0] in myList:
       print (i)

but it return to me:

1  2  435
2  4  900
22 3  384

because it finds, I suppose, a match between the "22" of myList and the "2" of the external file. Does someone know how to fix this problem?

Upvotes: 0

Views: 4877

Answers (3)

U13-Forward
U13-Forward

Reputation: 71580

Try the below solution, i just did a simple list comprehension, i split each line of the file by ' ' and get the first element of it and check if it starts with any of the elements of myList and if it is, strip it so the '\n' won't be in the strings

myList = [1, 22]
with open('test.txt') as f:
    print([i.strip() for i in f.readlines() if int(i.split(' ')[0]) in myList])

Output:

['1  2  435', '22 3  384']

If you want it to display it like what you wanted, try the below code

myList = [1, 22]
with open('test.txt') as f:
    lstcomp = [i.strip() for i in f.readlines() if int(i.split(' ')[0]) in myList]
    for i in lstcomp:print(i)

Output:

1  2  435
22 3  384

Upvotes: 0

Austin
Austin

Reputation: 26039

This should work. Read the file line by line, check if first word in list and print.

lst = [1, 22] 
with open('file.txt') as f:
    for line in f:
        words = line.split()
        if int(words[0]) in lst:
            print(line)

# 1  2  435
# 22 3  384                                                 

Upvotes: 4

Rakesh
Rakesh

Reputation: 82765

use str.split to split the line by space. And then compare

Ex:

myList = [1, 22]
with open(filename, "r") as infile:
    for line in infile:
        val = line.split()
        if int(val[0]) in myList:
            print(line.strip())

Output:

1  2  435
22 3  384

Upvotes: 0

Related Questions