2013-11-27 263 views
0

我的程序將導入由具有最大的文本的15行用戶創建的文件中它(下面的例子)列表過濾

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

ř 程序然後過濾所有具有#VALUE 1線大於2和#值2大於3000並打印出他們的#ID,忽略其餘部分。

這是我迄今所做

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 
+1

這是過濾,而不是排序。 –

+0

哦,是的,你是對的。 – user2958069

+0

並且'和'不會加入這兩個列表。 –

回答

3

使用你的代碼爲出發點:

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) 

異常中放置需要處理的非整數值。

+0

有幫助,謝謝! – user2958069

+1

@ user2958069:'filename ='input.txt''就夠了。不需要括號。 'infile'也應該關閉。或者你可以使用'open(filename)作爲infile:'和'infile'將被自動關閉。 – pepr