2017-07-17 14 views
1

我有下面的代碼,並希望返回的主題,對於任何給定的老師的最有效的方法:與由分隔符分隔的兩個值的列表,訪問在第二列第二場

注:列表alldata包含格式的數據:

['Mr Moose : Maths', 'Mr Goose: History', 'Mrs Marvin: Computing'] 

其中'Mr Moose:Maths'是列表中的第一個元素。 我希望得到的數學和歷史和計算,對於搜索對於任何給定的老師。

代碼

#Search for a teacher, and return the subject they teach 
"""File contents 
Mr Moose : Maths 
Mr Goose: History 
Mrs Cook: English 

""" 

alldata=[] 
col_num=0 
teacher_names=[] 
delimiter=":" 

def main(): 
     with open("teacherbook.txt") as f: 
      for line in f.readlines(): 
        alldata.append((line.strip())) 
      print(alldata) 


      print() 
      print() 

      for x in alldata: 
        teacher_names.append(x.split(delimiter)[col_num].strip()) 


      teacher=input("Enter teacher you are looking for:") 
      if teacher in teacher_names: 
        print("..and the subject they teach is:",teacher_names[2]) 
      else: 
        print("No") 

main() 

我很想知道,如果這個代碼可以只通過增加一個簡單的線條來在那裏我有teacher_names [2]和/或任何解決方案,更優雅固定,即顯示瞭如何直接搜索一個文件給定的名稱(如駝鹿先生)並返回下一個場(在這種情況下,數學)。這裏的過程看起來很艱難,而不是使用csv處理的過程。

+3

是列表中唯一的每個元素的第一個元素?如果是這樣,爲什麼不把它們解析成字典呢? – MooingRawr

+0

選擇不同的數據結構。使用這樣的字符串沒有意義,然後解析字符串。只需使用一個字典,甚至是一個元組列表。 –

+1

另外,順便說一句,不要使用'在f.readlines()'行,就用'的行F'。後者是更有效,這一個接一個讀取行,你不必將整個文件讀入內存,並兌現像前行的列表。 –

回答

4

我會推薦列表轉換爲dict ionary可快速方便的查找。

這是如何在你的列表轉換爲一個字典:

In [550]: t_list = ['Mr Moose : Maths', 'Mr Goose: History', 'Mrs Marvin: Computing'] 

In [556]: t_dict = dict(tuple(map(str.strip, x.split(':'))) for x in t_list); t_dict 
Out[556]: {'Mr Goose': 'History', 'Mr Moose': 'Maths', 'Mrs Marvin': 'Computing'} 

正如指出的那樣,如果你能保證周圍:一個空間,可以縮短map(str.strip, x.split(':'))x.split(' : ')

現在,如果你想有一個特定的老師教的主題,所有你需要做的是用字典索引得到它:

In [557]: t_dict['Mr Moose'] 
Out[557]: 'Maths' 
+2

如果你確信你的數據總是能夠很好地形成,你可以用'x.split'(':')替換'map(str.strip,x.split(':'))'' 編輯:Aaaaand忽略我,因爲我誤解了示例數據。 –

+0

@ JakeConkerton - 美的確,謝謝。 –

1

我同意,字典查找是最好的。另一種方法來解決這個問題:

>>> with open('teacherbook.txt') as teacher_file: 
...  alldata = [line.split(':') for line in teacher_file] 
# [['Mr Moose', 'Maths'], ['Mr Goose', 'History'], ... ] 


>>> teacher_dict = {line[0]: line[1].strip() for line in alldata} 
# {'Mr Moose': 'Maths', 'Mr Goose': 'History', ... } 
相關問題