x = ["Moon","Earth","Jupiter","Neptune","Earth","Venus"]
get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
print(get_indexes("Earth",x))
答案 0 :(得分:1)
结合使用list comprehension
和enumeration
可以解决问题。
indices = [i for i, d in enumerate(x) if d == "Earth"]
答案 1 :(得分:1)
仅对 1 个项目使用list.index
:
>>> x = ["Moon","Earth","Jupiter","Neptune","Earth","Venus"]
>>> x.index("Earth")
1
对于所有索引,作为lambda
函数:
>>> indexes = lambda l, k: [i for i, e in enumerate(l) if e == k]
>>> indexes(x, "Earth")
[1, 4]