查找與謂詞匹配的序列中的第一個元素

| | |

我想要一種慣用的方法來查找列表中與謂詞匹配的第一個元素。

當前代碼非常難看:

[x for x in seq if predicate(x)][0] 

我考慮過改成:

from itertools import dropwhile dropwhile(lambda x: not predicate(x), seq).next() 

但一定有更優雅的東西...如果它返回一個 None 值就好了如果沒有找到匹配項,而不是引發異常。

我知道我可以定義一個類似的函數:

def get_first(predicate, seq): for i in seq : if predicate(i): return i return None 

但是用這樣的實用函數開始填充代碼是非常無味的(人們可能不會注意到它們已經在那裡,所以它們往往會隨著時間的推移而重複)如果有已經提供相同的內置插件。

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method