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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)