Python - 索引超出范围错误

标签 python

我有来自 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/

相关文章:

python - 有没有更有效的方法来枚举 python 或 R 中离散随机变量的每个可能结果的概率?

python - 使用 dtype float 将 pandas.Multiindex 转换为 numpy.ndarray

PHP 相当于 Python 的 `str.format` 方法?

python - 随机列表中的对象属性在 Python 中不可访问

python - 替换照片中除现有黑白像素之外的所有颜色

Python 3 列表切片引发索引错误

python - 如何更有效地在 python 中搜索大列表?

python - 了解 django.shortcuts.redirect

Python 全局变量不更新

python - 使用 python 从 JSON 文件中删除一些特定对象,然后将文件推送到 Elasticsearch Index