user2958069
user2958069

Reputation: 93

list filtering in python

my program will import a file created by user having maximum of 15 lines of text in it(examples below)

#ID #value1 # value2
445 4 9000 
787 2 4525 
405 4 3352 
415 1 2854 
455 2 5500 

r The program then filter all the lines that have #value 1 larger than 2 and #value 2 larger than 3000 and print out their #ID, ignoring the rest.

here's what i have done so far

filename = ('input.txt')
infile = open(filename, 'r')
list_id = []
list_value1 = []
list_value2 = []
masterlist = []
for line in infile:
id, value1, value2 = line.split()
list_id.append(id)
list_value1.append(value1)
list_value2.append(value2)
masterlist.append(list_id)
masterlist.append(list_value1)
masterlist.append(list_value2)

#filtering part
sort = [i for i in masterlist[1] if i > 2 ] and [p for p in masterlist[2] if p > 3000]

#do something here to print out the ID of the filtered lines

Upvotes: 0

Views: 142

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

Using your code as a starting point:

filename = ('input.txt')
infile = open(filename, 'r')
ids = []
for line in infile:
    id, value1, value2 = line.split()
    if int(value1) > 2 and int(value2) > 3000:
        ids.append(id)

Put in exception handling for non-integer values as needed.

Upvotes: 3

Related Questions