【发布时间】:2012-11-21 19:39:03
【问题描述】:
假设我有这份清单
x = [1,2,3,1,5,1,8]
有没有办法找到1 在列表中的每个索引?
【问题讨论】:
-
你是什么意思找到?你想要什么输出?你试过什么?
假设我有这份清单
x = [1,2,3,1,5,1,8]
有没有办法找到1 在列表中的每个索引?
【问题讨论】:
当然。列表理解加上 enumerate 应该可以工作:
[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]
【讨论】:
print ([ i for i,z in enumerate(x) if z == 1 ])
list.index 的文档(还有一个有用的提示:启动Python 解释器并输入help(list.index))。
提问者要求使用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 的解决方案更冗长,我认为它是更惯用的 Python。
【讨论】: