列表索引如何在python

时间:2016-06-11 16:05:10

标签: python python-3.x

我正在尝试理解列表和索引在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

3 个答案:

答案 0 :(得分: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 :(得分: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

答案 2 :(得分:0)

https://jsfiddle.net/davidsekar/qr6gecj9/1/index返回列表中第一次出现的元素的索引:

  

list.index(x)

     

返回值为x的第一个项目列表中的索引。如果没有这样的项目,则会出错。