如何解决使用for循环迭代并引用lst [i]时发生TypeError / IndexError
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
许多人使用索引来摆脱习惯,因为他们习惯于从其他编程语言中那样做。 遍历值更加方便和可读:
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
循环遍历这样的列表:
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
循环怎么了?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。