开发者

Get specific object from a list with a certain parameter

开发者 https://www.devze.com 2023-02-06 21:24 出处:网络
I have a list of Account objects in self.accounts, and I know that only one of them will have a type attribute equal to \'equity\'.What is the best (most pythonic) w开发者_StackOverflow中文版ay to get

I have a list of Account objects in self.accounts, and I know that only one of them will have a type attribute equal to 'equity'. What is the best (most pythonic) w开发者_StackOverflow中文版ay to get only that object from the list?

Currently I have the following, but I'm wondering if the [0] at the end is superfluous. Is there a more succinct way to do this?

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


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

or

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


"Pythonic" means nothing. There is probably not any more "Succinct" solution than yours, no.

Ignacios solution has the benefit of stopping once it finds the item. Another way of doing it would be:

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

Which perhaps is more readable. Readability is Pythonic. :)

Edit: Improved after martineaus suggestions. Made it into a complete method.


It's such a common need in Python but afaik there is no built in way to do it. You could also do:

return next(filter(lambda x: x.type == 'equity', self.accounts))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号