使用for循环迭代并引用lst [i]时发生TypeErrorIndexError

使用for循环迭代并引用lst [i]时发生TypeErrorIndexError,第1张

使用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

许多人使用索引来摆脱习惯,因为他们习惯于从其他编程语言中那样做。 在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


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5631411.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存