2016-06-11 91 views
0

工作我試圖瞭解名單和指標如何在Python工作如何列表索引在Python

所以我想這個代碼打印在列表

tokens = ["and", "of", "then", "and", "for", "and"] 
for word in tokens: 
    word_index = tokens.index(word) 
    print(word_index, word) 
列表中的所有物品與其對應的索引

它給了我這個輸出

0 and 
1 of 
2 then 
0 and 
4 for 
0 and 

所以我的問題是,爲什麼"and"這裏有0代替0, 3, 5相同指數?

,我如何獲得

0 and 
1 of 
2 then 
3 and 
4 for 
5 and 
+0

https://docs.python.org/3/tutorial/datastructures.html – kfx

回答

3

我的問題所需要的輸出就是爲什麼「和」這裏有0,而不是0,3,5相同的指數?

爲什麼

這是因爲list.index()返回第一個出現的索引,這樣以來「和」第一索引0出現在列表中,這就是你將永遠得到。

解決方案

如果你想跟着指數,當您去嘗試enumerate()

for i, token in enumerate(tokens): 
    print(i, token) 

它給你想要的輸出:

0 and 
1 of 
2 then 
3 and 
4 for 
5 and 
1

使用enumerate

In [1]: tokens = ["and", "of", "then", "and", "for", "and"] 
In [2]: for word_index,word in enumerate(tokens): 
    ....:  print (word_index, word) 
    ....:  

輸出

0 and 
1 of 
2 then 
3 and 
4 for 
5 and 
+0

爲什麼選擇投票?即使我在接受的同一時間回答正確的答案。 –

0

Python documentationindex返回元素第一次出現在列表中的索引:

list.index(x)

返回的索引在列表中o f值爲x的第一項。如果沒有這樣的項目,這是一個錯誤。