索引如何在具有重复项的列表中工作?

How do indices work in a list with duplicates?

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

My question is why "and" here have the same index of 0 instead of 0, 3, 5?

为什么

这是因为 list.index() returns 是第一次出现的索引,所以由于 "and" 第一次出现在列表中的索引 0 中,这就是您将始终得到的。

解决方案

如果你想边走边跟着索引试试enumerate()

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

这给出了你想要的输出:

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

使用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

来自Python documentationindex、returns列表中元素第一次出现的索引:

list.index(x)

Return the index in the list of the first item whose value is x. It is an error if there is no such item.