从列表中获取具有特定参数的对象
我有一个包含多个账户对象的列表,放在self.accounts
里。我知道只有一个账户的type
属性是'equity'。我想知道,最好的(最符合Python风格的)方法是什么,来从这个列表中获取那个账户对象。
现在我用的是下面这段代码,但我在想,最后的[0]
是不是多余的。有没有更简洁的方法来实现这个?
return [account for account in self.accounts if account.type == 'equity'][0]
3 个回答
0
在Python中,这个需求非常常见,但据我所知,没有内置的方法可以做到这一点。你也可以这样做:
return next(filter(lambda x: x.type == 'equity', self.accounts))
4
“Pythonic”这个词其实没什么特别的意思。你的解决方案可能已经是最简洁的了,没错。
Ignacio的方案有个好处,就是一旦找到目标就会停止。还有另一种做法是:
def get_equity_account(self):
for item in self.accounts:
if item.type == 'equity':
return item
raise ValueError('No equity account found')
这种方式可能更容易理解。可读性就是Pythonic的精髓。:)
编辑:根据martineau的建议进行了改进,把它做成了一个完整的方法。
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()