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

时间:2017-07-17 15:40:18

标签: python list

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

注意:列表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处理。

2 个答案:

答案 0 :(得分:4)

我建议您将列表转换为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(' : ')

现在,如果您希望某位老师教授该科目,您需要做的就是使用dict索引来获取它:

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

答案 1 :(得分: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', ... }