在 ruby 中:
[[1,2],[2,3],[9,3]].find_index {|i| i.include?(3)}
返回 1
,这是包含 3 的数组中第一个元素的索引。Python 中是否有与此等效的内容?我查看了 List
的 index
方法,但它似乎没有将 lambda 作为参数。
最佳答案
我通常写类似的东西
>>> a = [[1,2],[2,3],[9,3]]
>>> next(i for i,x in enumerate(a) if 3 in x)
1
如果没有找到,你会得到一个StopIteration
异常,或者你可以传递一个默认值作为第二个参数返回:
>>> next(i for i,x in enumerate(a) if 99 in x)
Traceback (most recent call last):
File "<ipython-input-4-5eff54930dd5>", line 1, in <module>
next(i for i,x in enumerate(a) if 99 in x)
StopIteration
>>> next((i for i,x in enumerate(a) if 99 in x), None)
>>>
关于Python 相当于 Ruby 的 #find_index 和 lambda?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20804001/