Skip to main content
 首页 » 编程设计

list之从具有特定参数的列表中获取特定对象

2025年05月04日29itcoder

我在 self.accounts 中有一个 Account 对象列表,我知道其中只有一个对象的 type 属性等于“equity”。从列表中仅获取该对象的最佳(最 pythonic)方法是什么?

目前我有以下内容,但我想知道末尾的 [0] 是否多余。有没有更简洁的方法来做到这一点?

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

请您参考如下方法:

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

或

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