我有来自 Python 的示例文本,我正在处理它。
Afghanistan:32738376
Akrotiri:15700
Albania:3619778
Algeria:33769669
American Samoa:57496
Andorra:72413
Angola:12531357
Anguilla:14108
Antigua and Barbuda:69842
Argentina:40677348
Armenia:2968586
Aruba:101541
Australia:20600856
Austria:8205533
Azerbaijan:8177717
我有这段代码可以使用国家/地区名称和人口制作字典。
dct = {}
for line in infile:
line = line.strip()
words = line.split(":")
countryname = words[0]
population = int(words[1])
dct[countryname] = population
当我打印population时,它会打印所有值,但随后我得到population = int(words[1]) - IndexError:列表索引超出范围。我不明白我是如何收到此错误的,特别是当我打印国家/地区名称时,它绝对没问题,该错误仅发生在人口中。 Python 必须为两个变量访问相同数量的行,但似乎随着人口的增长,它试图访问更多的行,我不明白,因为它不会为国家/地区名称执行此操作。关于为什么会发生这种情况的任何想法。
最佳答案
您认为您的文件是完美的,但这是错误的。
try:
countryname = words[0]
population = int(words[1])
dct[countryname] = population
except IndexError:
print("Impossible convert line: %s " % line)
在这种情况下,我更喜欢使用日志而不是打印语句,但为了示例,我认为这是可以的。 如果需要,您还应该打印行号。
无论如何,尝试/异常(exception)的目的是避免在文件不符合您想要的格式时破坏程序。
关于Python - 索引超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35240267/