我在 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()
关于list - 从具有特定参数的列表中获取特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4779203/