在由分隔符分隔的两个值的列表中,访问第二列中的第二个字段

2024-06-26 13:59:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码,并希望最有效的方法返回主题,为任何给定的老师:

注意:列表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()

我很想知道这个代码是否可以通过在我有教师姓名[2]的地方添加一个简单的行和/或任何更优雅的解决方案来修复,即显示如何直接在文件中搜索给定的姓名(例如Moose先生)并返回下一个字段(在本例中为数学)。与使用csv处理相比,这里的过程看起来确实很艰巨


Tags: moose代码infornames数学老师history
2条回答

我建议您将列表转换为^{}词典,以便快速轻松地查找

以下是如何将列表转换为词典:

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(' : ')

现在,如果你想要某位老师教的科目,你所需要做的就是使用dict索引来获取它:

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', ... }

相关问题 更多 >