【发布时间】:2020-11-25 02:34:31
【问题描述】:
我在尝试为字典分配键和值的行收到错误“列表索引超出范围”。我试图将第二行中的项目命名为键,将第一个项目命名为值。我正在导入的文本文件如下所示:
A0101 伤寒脑膜炎
A0102 伤寒伴心脏受累
A0103 伤寒肺炎
A0104 伤寒性关节炎
def disease_to_code_dictionary() :
infile = open("ICD10.txt","r")
header_row = infile.readline() # skip the header row
dictionary = {}
for line in infile :
cells = line.split("\t") # split by the tab character
dictionary[cells[1]]=cells[0]
if len(cells) >= 2 : # only if the line had a tab
code = cells[0]
disease = cells[1]
disease = disease.lower() # lowercase
disease = disease.replace("\"","") # remove all double quotes
infile.close()
【问题讨论】:
-
错误是"list index out of range",所以错误是索引大于列表。该线路是
dictionary[cells[1]]=cells[0]。该列表是cells。索引是0和1。这能解释清楚吗? -
感谢您的回复。是的,没错。因此,由于我正在创建字典,因此我不确定在分配键和值时缺少什么。我认为 0 和 1 可以识别第 1 行和第 2 行中的项目。由于列表有多行,我是否必须包括不仅仅是 0 和 1?
-
不,
cells不包含行。您应该使用调试器或至少print变量值来查看发生了什么。试试print(line)和print(cells)。 -
啊...我在字典[line[1]]=line[0] 行中用'line'替换了'cells'。我认为这就是问题所在。谢谢!
标签: python python-3.x dictionary key