“是否存在用于查找元素向量索引的python函数?”

时间:2019-05-03 04:49:29

标签: python python-3.x

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))

2 个答案:

答案 0 :(得分:1)

结合使用list comprehensionenumeration可以解决问题。

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]