Skip to main content
 首页 » 编程设计

python之在列表中查找项目索引

2025年05月04日12kevingrace

这是一个非常简单的问题,但我似乎无法理解为什么我没有得到它。

def listindex(): 
    li = ['a', 'e', 'a', 'd', 'b', 'a', 'e'] 
    for x in li: 
        if x == 'a': 
            print(li.index(x)) 

结果:

0 
0 
0 

预期结果:

0 
2 
5 

虽然它遍历所有项目我只得到第一个项目索引,这是为什么呢?也建议即使它很简单。

请您参考如下方法:

index 仅返回第一个元素的索引。来自docs

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

使用enumerate反而。当您使用 enumerate 进行迭代时,您可以在循环中访问元素及其索引:

>>> li = ['a', 'e', 'a', 'd', 'b', 'a', 'e'] 
>>> for i,element in enumerate(li): 
...     if element == 'a': 
...        print(i) 
...  
0 
2 
5