簡體   English   中英

Python相當於Ruby的#find_index與lambda?

[英]Python equivalent of Ruby's #find_index with lambda?

在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中沒有直接的等效函數。

您可以使用enumerate列表理解獲得多個indice:

>>> [i for i, xs in enumerate([[1,2],[2,3],[9,3]]) if 3 in xs]
[1, 2]

如果只需要第一個索引,則可以使用next表達式:

>>> next(i for i, xs in enumerate([[1,2],[2,3],[9,3]]) if 3 in xs)
1
>>> next((i for i, xs in enumerate([[1,2],[2,3],[9,3]]) if 999 in xs), 'no-such-object')
'no-such-object'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM