这是一个非常简单的问题,但我似乎无法理解为什么我没有得到它。
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
关于python - 在列表中查找项目索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33349774/