使用for循环迭代并引用lst [i]时发生TypeError/IndexError [英] TypeError/IndexError when iterating with a for loop, and referencing lst[i]
问题描述
我正在使用 for
循环遍历这样的列表:
I'm using a for
loop to iterate over a list like this:
lst = ['a', 'b', 'c']
for i in lst:
print(lst[i])
但是这一定有问题,因为它引发了以下异常:
But there must be something wrong with that, because it throws the following exception:
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
:
And if I try the same thing with a list of integers, it throws an IndexError
instead:
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
循环遍历列表的值,而不是 indices :
Python's for
loop iterates over the values of the list, not the indices:
lst = ['a', 'b', 'c']
for i in lst:
print(i)
# output:
# a
# b
# c
这就是为什么如果尝试使用 i
索引 lst
的原因,则会出现错误:
That's why you get an error if you try to index lst
with 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中,您几乎不需要索引.遍历值更加方便和可读:
Many people use indices to iterate out of habit, because they're used to doing it that way from other programming languages. In Python you rarely need indices. Looping over the values is much more convenient and readable:
lst = ['a', 'b', 'c']
for val in lst:
print(val)
# output:
# a
# b
# c
如果您确实需要循环中的索引,则可以使用 枚举
函数:
And if you really need the indices in your loop, you can use the enumerate
function:
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循环迭代并引用lst [i]时发生TypeError/IndexError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!