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

标签 list python

我在 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/

相关文章:

Python 字典和类中的列表更新和追加

java - 根据标记值对 java 列表中的 XML 行进行排序

python - 如何在不知道索引的情况下从 numpy 数组中删除对象

python - 使用 Pandas 数据框计算累积返回

python - 如何在 Python 中将一个列表附加到另一个索引匹配的列表?

python - 查找列表元素的所有组合,包括重复元素

python - 如何使用python查找列表中最大数字出现的次数?

python - 检查 pyshark-Python 中当前数据包中是否存在图层

python - 奥杜 10 : Getting a view like invoice _line_ids from Invoice module

python - 在保持值(value)的同时在循环内进行比较