2011-01-24 61 views
1

我在self.accounts帳戶對象的列表,我知道,只有其中一人將有一個type屬性等於「公平」。什麼是最好的(最pythonic)的方式來從列表中只得到該對象?獲取特定對象,具有一定的參數

目前我有以下的,但我想知道如果[0]末是多餘的。有沒有更簡潔的方法來做到這一點?

return [account for account in self.accounts if account.type == 'equity'][0]

+0

「我想知道,如果[0]到底是多此一舉」?爲何想知道?嘗試一下。嘗試後,嘗試其他一些方法,如打印表達式的中間結果。 – 2011-01-24 11:11:03

+0

不,這不是多餘的,因爲它決定了你是否返回一個列表(可能有零個或多個元素)或者只是列表中的第一個元素(並假設它不是空的)。如果這就是你想要的,那就相當簡潔。 – martineau 2011-01-24 14:08:49

回答

7
return next(account for account in self.accounts if account.type == 'equity') 

return (account for account in self.accounts if account.type == 'equity').next() 
4

「Python化」 意味着什麼。可能沒有比你更多的「簡潔」解決方案了,不。

Ignacios解決方案具有停止一旦找到該項目的效益。另一種做法是:

def get_equity_account(self): 
    for item in self.accounts: 
     if item.type == 'equity': 
      return item 
    raise ValueError('No equity account found') 

這或許更具可讀性。可讀性是Pythonic。 :)

編輯:martineaus建議後好轉。把它變成一個完整的方法。