[英]Select an element that satisfies a condition
我想從(很長)列表中選擇一個滿足條件的特定元素。 在我的特定情況下,列表中的每個項目都是一個類,而我想要的條件是例如item.id == 1。
我開始
[item for item in collection if item.id == 1]
但我不想遍歷整個列表,因為我敢肯定只有一個滿足條件的元素。
另一個選擇是
def check(collection):
for item in collection:
if item.id == 1:
return item
有沒有更有效的方法? Python 3是否為此提供了內置功能? 另一個選擇可能是預處理列表以獲得字典,例如
{item.id : item for item in collection}
要獲得滿足條件的第一個元素,請使用忍者的答案中概述的next()
。
為了獲得一個滿足條件的元素並檢查它是否唯一,我使用以下函數:
def single(seq):
"""Checks that the sequence has a single element and returns it."""
"""Analogous to .Net LINQ's Single()"""
if hasattr(seq,"__len__"):
assert len(seq)==1
return seq[0]
else:
i=iter(seq)
try: value=i.next()
except StopIteration: raise AssertionError()
try: i.next()
except StopIteration: return value
else: raise AssertionError()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.