2015-11-02 94 views
-7

我现在拥有的是:原始输入和读取数据

f = open("SampleList.txt", "r") 

x = f.readlines() 
y = [] 


for i in range (len(x)): 
    y.append(x[i].rstrip('\n').split(',')) 


for i in range(len(y)): 
z = y[i] 
print z 

什么它给的回复是:

['100000', 'Weasely ', 'Bill ', '9', '1 Discipline', '0'] 
['120001', 'Weasely ', 'Fred ', '10', '1 Discipline', '0'] 
['120002', 'Weasley ', 'George ', '6', '1 Tardies', '0'] 
['130003', 'Weasley ', 'Ronald ', '10', 'OK', '0'] 
['130004', 'Longbottom ', 'Neville ', '5', '1 Absence', '0'] 
['130005', 'Potter ', 'Harry ', '5', 'OK', '0'] 
['130006', 'MAlfoy ', 'Draco ', '5', '1 Owes more than $5', '$150.00'] 
['100118', 'The House Elf ', 'Dobbey ', '7', 'OK', '0'] 
['100011', 'LaStrange ', 'Belatrix ', '8', '1 Discipline', '0'] 
['100170', 'Dumbledore ', 'Albus ', '7', '1 Administration', '0'] 

我需要它做的事知道是不是要问说一个学生输入他们的第一个项目“10000”的学生ID号的原始输入,依此类推。 然后它需要搜索并确定这个数字是否有效,并且如果它发现它首先打印出学生姓名和最后的名字,并且他们是否符合这个条件,那就是1学科,1 Tardies,就像OK一样。 任何帮助将得到极大的赞赏

+1

使用字典。 –

+3

多比在他的名字中没有e ... –

+1

虽然我们的名字是Bellatrix Lestrange。 –

回答

1

读取文件内容时使用字典。

字典中的数字文件中的ID号码(每个行中的第一个项目在split之后)都被键入,词典中的每个条目都将包含行的其余部分,如list

def student_info(student): 
    d = {} 
    with open("SampleList.txt", "r") as f: 
     x = f.readlines() 

    for i in range (len(x)): 
     ln = x[i].rstrip('\n').split(',') 
     # Add this ID to the dictionary keys, and add the remainder of the line as the value for that key 
     d[ln[0]] = ln[1:] 

    if student in d: 
     return(d[student][1] + ' ' + d[student][0] + ' ' + d[student][-2]) 
    else: 
     return 'invalid student id#' 

studentID = raw_input('Enter your student ID#: ') 
print student_info(studentID)