Python 相当于 Ruby 的 #find_index 和 lambda?

标签 python ruby list

在 ruby 中:

[[1,2],[2,3],[9,3]].find_index {|i| i.include?(3)}

返回 1,这是包含 3 的数组中第一个元素的索引。Python 中是否有与此等效的内容?我查看了 Listindex 方法,但它似乎没有将 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/

相关文章:

python - 从终端测试 Google App Engine 应用程序(python cli)

python - 使用 pyinstaller 时出现错误 "has no attribute ' reduce_cython”

带有行号的 Ruby grep

javascript - Rails 解析 Ransack 参数并提交

c++ - 从 C++ 中的列表中删除元素

list - 丢弃索引中的元素,元素元组

list - 方案:找出 "complex"元素是否在 "complex"列表中

python - 导入错误 : cannot import name 'load_entry_point' (PIP)

ruby - 如何使用 Ruby 电子表格库格式化特定单元格?

python - pycuda.debug 实际上做了什么?