TypeError/IndexError 使用 for 循环迭代并引用 lst[i] 时

TypeError/IndexError when iterating with a for loop, and referencing lst[i]

我正在使用 for 循环遍历这样的列表:

lst = ['a', 'b', 'c']
for i in lst:
    print(lst[i])

但这肯定有问题,因为它抛出了以下异常:

Traceback (most recent call last):
  File "untitled.py", line 3, in <module>
    print(lst[i])
TypeError: list indices must be integers or slices, not str

如果我用整数列表尝试同样的事情,它会抛出一个IndexError

lst = [5, 6, 7]
for i in lst:
    print(lst[i])
Traceback (most recent call last):
  File "untitled.py", line 4, in <module>
    print(lst[i])
IndexError: list index out of range

我的 for 循环有什么问题?

Python 的 for 循环迭代列表的 values,而不是 indices

lst = ['a', 'b', 'c']
for i in lst:
    print(i)

# output:
# a
# b
# c

这就是为什么如果您尝试使用 i:

索引 lst 时会出现错误的原因
>>> lst['a']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not str
>>> lst[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

许多人出于习惯使用索引进行迭代,因为他们习惯于从其他编程语言中这样做。 在 Python 中,您很少需要索引。 遍历值更加方便和可读:

lst = ['a', 'b', 'c']
for val in lst:
    print(val)

# output:
# a
# b
# c

如果您真的需要循环中的索引,您可以使用enumerate函数:

lst = ['a', 'b', 'c']
for i, val in enumerate(lst):
    print('element {} = {}'.format(i, val))

# output:
# element 0 = a
# element 1 = b
# element 2 = c

推论:命名你的循环变量以避免混淆和错误代码

  • for i in lst 是一个糟糕的名字
    • 表明它是一个索引,我们可以而且应该这样做 lst[i],这是胡说八道,并抛出错误
    • 像 i、j、n 这样的名称通常只用于索引
  • 良好:for x in lstfor el in lstfor lx in lst
    • 没有人会尝试写 lst[el];名称的选择非常明显它不是没有索引,并且可以保护您免于胡说八道。

总结:

  • Python for 循环变量采用列表中的值,而不是其索引
  • 通常你不需要索引,但如果需要,请使用 enumerate() : for i, x in enumerate(list): ...
  • 直接遍历列表(不是它的索引,并查找每个条目)通常是更好的习惯用法