我有一个列表
array_list=[-37, -36, -19, -99, 29, 20, 3, -7, -64, 84, 36, 62, 26, -76, 55, -24, 84, 49, -65, 41]
当我尝试使用以下代码与索引相关的打印索引和价值进行迭代时
for value in array_list:
print(array_list.index(value), array_list[array_list.index(value)])
我将获得以下输出:
0 -37
1 -36
2 -19
3 -99
4 29
5 20
6 3
7 -7
8 -64
9 84
10 36
11 62
12 26
13 -76
14 55
15 -24
9 84 # I want the value as 16 instead of 9 (position of 84 in list)
17 49
18 -65
19 41
在索引16时,它为我的索引值为9。我不确定为什么要给我16个索引值。
我该如何修复?
list.index(..)
返回 list
中元素首次出现的值。例如:
>>> my_list = [1,2,3,1,2,5]
>>> [(i, my_list.index(i)) for i in my_list]
[(1, 0), (2, 1), (3, 2), (1, 0), (2, 1), (5, 5)]
# Here, 0th index element is the number
# 1st index element is the first occurrence of number
如果要在迭代期间获得元素的位置,则应使用 enumerate
进行迭代。例如:
>>> [(i, n) for n, i in enumerate(my_list)]
[(1, 0), (2, 1), (3, 2), (1, 3), (2, 4), (5, 5)]
# Here, 0th index element is the number
# 1st index element is the position in the list
您可以参考Python的列表文档,其中说:
list.index(x(
返回值为x的第一个项目列表中的索引。如果没有这样的项目,这是一个错误。
您正在向其询问该值的第一个条目的索引(然后使用该索引(。如果您想要迭代(用于循环(找到的索引,请尝试for i,value in enumerate(array_list)
。在列表上迭代会产生其包含的项目,而不是指列表。