Reputation: 24675
I am trying to compare a list with the lines that are read from a text file. I asked a similar question here, but that does not work since the data are read from file and each line is splitted.
Assme a data file looks like
2 3 5
1 2 7 8 2
1 4 3 4 6
I read that file using
fs = open("in.txt")
lines = [line.split() for line in fs if line.strip()]
Then, I define a list like this
seen = []
seen.append(1)
seen.append(2)
Next, I compare the queue with each line to finda match using
take = [row for row in lines if row[:2] == seen]
However, take is empty although it should be 1 2 7 8 2. The complete code is
fs = open("in.txt")
lines = [line.split() for line in fs if line.strip()]
seen = []
seen.append(1)
seen.append(2)
take = [row for row in lines if row[:2] == seen]
if len(take) != 0:
print(take)
else:
print("no match")
As I debug the program I see that each line of the file is presented like ['1', '2', '7', '8', '2']
while the seen
list looks like [1 2]
. How can I fix that?
Upvotes: 0
Views: 164
Reputation: 1505
When you are reading the input file in a list, the content of the list is strings.. You have only to type cast each entry...
fs = open("in.txt")
lines = [[int(strNumber) for strNumber in line.split()] for line in fs if line.strip()]
The rest should be similar.. Perhaps you should also handle exception if the content is not convertable to a integer..
Upvotes: 1