2024-05-20 12:29:00 发布
网友
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))
list comprehension和enumeration的组合可以达到这个目的
list comprehension
enumeration
indices = [i for i, d in enumerate(x) if d == "Earth"]
对于1项目,请使用list.index:
list.index
>>> x = ["Moon","Earth","Jupiter","Neptune","Earth","Venus"] >>> x.index("Earth") 1
对于所有索引,作为lambda函数:
lambda
>>> indexes = lambda l, k: [i for i, e in enumerate(l) if e == k] >>> indexes(x, "Earth") [1, 4]
list comprehension
和enumeration
的组合可以达到这个目的对于1项目,请使用
list.index
:对于所有索引,作为
lambda
函数:相关问题 更多 >
编程相关推荐