使用for循环迭代并引用lst [i]时发生TypeError / IndexError
问题内容:
我正在使用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
这就是为什么在尝试使用以下索引lst
时会出错的原因i
:
>>> 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