2015-11-02 112 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)