【发布时间】:2017-11-09 13:04:45
【问题描述】:
如果我在列表中使用 .index ,它将始终返回出现的第一个元素。但是如果它们是重复的并且我也想要它们的索引怎么办? 例如:
listm=["shell","shell","use"]
listm.index("shell")
它将返回 0,但有 2 个 "shell"s。我如何获得两者的索引?
【问题讨论】:
标签: python python-3.x
如果我在列表中使用 .index ,它将始终返回出现的第一个元素。但是如果它们是重复的并且我也想要它们的索引怎么办? 例如:
listm=["shell","shell","use"]
listm.index("shell")
它将返回 0,但有 2 个 "shell"s。我如何获得两者的索引?
【问题讨论】:
标签: python python-3.x
通过使用enumerate 的列表推导:
>>> ind = [i for i, j in enumerate(listm) if j == 'shell']
>>> print(ind)
[0, 1]
【讨论】:
使用:list comprehension + enumerate,
In [26]: listm = ["shell","shell","use"]
In [27]: [i for i,j in enumerate(listm) if j == "shell"]
Out[27]: [0, 1]
【讨论】: