假设我有这个列表:
x = [1,2,3,1,5,1,8]
有没有一种方法可以找到列表中每个
1
的索引?[i for i, z in enumerate(x) if z == 1]
并且证明:
>>> x = [1, 2, 3, 1, 5, 1, 8]
>>> [i for i, z in enumerate(x) if z == 1]
[0, 3, 5]
x.index
进行操作? - Keenanlist.index
的文档(还有一个有用的提示:启动Python解释器并键入help(list.index)
)。 - tzot提问者要求使用 list.index
来解决问题,这里是一个这样的解决方案:
def ones(x):
matches = []
pos = 0
while True:
try:
pos = x.index(1, pos)
except ValueError:
break
matches.append(pos)
pos += 1
return matches
它比mgilson的解决方案更冗长,我认为mgilson的解决方案更符合Python惯用法。