我有以下代码,并且希望为任何给定的老师提供最有效的返回主题的方法:
注意:列表 alldata 以以下格式保存数据:
['Mr Moose : Maths', 'Mr Goose: History', 'Mrs Marvin: Computing']
其中"穆斯先生:数学"是列表中的第一个元素。 我希望进入数学,历史和计算,对于任何被搜索的给定老师。
法典
#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] 和/或任何更优雅的解决方案中添加一个简单的行来修复,即显示如何直接在文件中搜索给定名称(例如 Moose 先生(并返回下一个字段(在本例中为 Maths(。与使用 csv 处理相比,这里的过程看起来确实很艰巨。
我建议将您的列表转换为dict
,以便快速轻松地查找。
这是将列表转换为字典的方法:
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'
我同意,字典查找是最好的。解决问题的另一种方法:
>>> 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', ... }