我正在使用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
循环遍历列表的值,而不是索引:
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 lst
,for el in lst
,for lx in lst
.- 没有人会尝试写
lst[el]
;名字的选择非常明显地表明它不是没有索引,并保护你不写废话。
- 没有人会尝试写
总结:
- Python for 循环变量假定列表中的值,而不是其索引
- 通常您不需要索引,但如果需要,请使用
enumerate()
:for i, x in enumerate(list): ...
- 通常更好的习惯用法是直接迭代列表(不是其索引,并查找每个条目(