2013-11-27 63 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