gpt4 book ai didi

python - 使用 for 循环迭代并引用 lst[i] 时出现 TypeError/IndexError

转载 作者:行者123 更新时间:2023-12-01 01:30:49 24 4
gpt4 key购买 nike

我正在使用 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

关于python - 使用 for 循环迭代并引用 lst[i] 时出现 TypeError/IndexError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52890793/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com