python - 索引错误: list index out of range

标签 python for-loop dictionary text

我在 Windows 10 上使用 Python 3.5,32 位。

虽然我知道有关此错误消息的问题已被频繁询问和解答,但我仍然无法弄清楚为什么我的代码或相应的 .txt 文件实际上会导致此错误。

该代码是 Python 初学者书籍的 1:1 副本,也是该代码的衍生版本,其中我仅更改了字典的名称并使用了另一个工作正常的 .txt 文件。

这是代码:

woerter={}
fobj=open("Woerterbuch.txt","r")
for line in fobj:
   zuordnung=line.split(" ")
   woerter[zuordnung[0]] = zuordnung[1]
fobj.close()

print(woerter)

这是相应的 .txt 文件:

Spain Spanien
Germany Deutschland
Sweden Schweden
France Frankreich
Italy Italien

该代码将产生以下错误:

    Traceback (most recent call last):
      File "C:\Users\Christian\Desktop\Python-Programme\Dateiausleseprogramm2.py", line 5, in <module>
        woerter[zuordnung[0]] = zuordnung[1]
    IndexError: list index out of range

最佳答案

您给定的代码和文件不会重现该错误。但是,如果我向文件中添加另一个换行符(空行),则会产生您给出的错误。我删除了两个文件中的前导空格,并向您的代码添加了一些跟踪打印语句:

woerter={}
fobj=open("Woerterbuch.txt","r")
for line in fobj:
   zuordnung=line.split(" ")
   woerter[zuordnung[0]] = zuordnung[1]
   print (zuordnung)
fobj.close()

print(fobj)
print(woerter)

输入文件末尾没有空行,得到我想要的输出:

['Spain', 'Spanien\n']
['Germany', 'Deutschland\n']
['Sweden', 'Schweden\n']
['France', 'Frankreich\n']
['Italy', 'Italien\n']
<_io.TextIOWrapper name='so.txt' mode='r' encoding='UTF-8'>
{'Germany': 'Deutschland\n', 'Sweden': 'Schweden\n', 'Italy': 'Italien\n', 'Spain': 'Spanien\n', 'France': 'Frankreich\n'}

使用空行,我可以重现您的问题。 print 语句使直接原因变得显而易见:

['Spain', 'Spanien\n']
['Germany', 'Deutschland\n']
['Sweden', 'Schweden\n']
['France', 'Frankreich\n']
['Italy', 'Italien\n']
['\n']
Traceback (most recent call last):
  File "so.py", line 6, in <module>
    woerter[zuordnung[0]] = zuordnung[1]
IndexError: list index out of range

请注意,我从您发布的数据文件中删除了前导空格:这使得第一个分割始终为“”,后面还有两个字段。

关于python - 索引错误: list index out of range,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40470668/

相关文章:

python - 在一个 Python 数据帧/字典中搜索另一个数据帧中的模糊匹配

python - 将句子的字符串表示形式列表转换为词汇集

python - 为什么 Cython Decorator 版本比 Cython Pyx 版本慢?

Java - For 循环将无法完成,仅三个循环后就会崩溃

python - 使用 __getattr__ 和 __setattr__ 功能实现类字典对象

javascript - 如何使用 react 在传单的图层控制选择上添加标题?

python - 如何根据 python 中的名称选择多个列?

python - 如何优化循环和条件语句?

python - 使用for循环的结果在python中创建新列表

c++ - 从多个 map<key,value> 中搜索的最佳方式是什么?