2017-04-20 66 views
1

我有一個列表值被設置爲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

回答

0

你問它的第一個條目與該值的索引(然後使用該索引)。如果您想要迭代(for循環)找到的索引,請嘗試for i,value in enumerate(array_list)。遍歷列表會產生它包含的項目,而不是返回列表。

4

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。如果沒有這樣的項目,這是一個錯誤。