值被设置为9

问题描述:

我有一个列表值被设置为9

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作为指标值。

我该如何解决这个问题?

+0

任何人都可以建议为什么它的行为如此吗? – user3453044

+2

是的,我确定'list.index'上的文档可以。 –

+0

索引返回值的第一个实例的索引。 – roganjosh

你问它的第一个条目与该值的索引(然后使用该索引)。如果您想要迭代(for循环)找到的索引,请尝试for i,value in enumerate(array_list)。遍历列表会产生它包含的项目,而不是返回列表。

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's List Document,它说:

list.index(X)

返回的第一个项目,其列表中的索引值是x。如果没有这样的项目,这是一个错误。