python - 在 Python 中按属性获取对象列表中的索引

标签 python list indexing

我有具有属性 id 的对象列表,我想找到具有特定 id 的对象的索引。我写了这样的东西:

index = -1
for i in range(len(my_list)):
    if my_list[i].id == 'specific_id'
        index = i
        break

但是看起来不太好。有没有更好的选择?

最佳答案

当您需要 for 循环中的值和索引时,请使用 enumerate:

for index, item in enumerate(my_list):
    if item.id == 'specific_id':
        break
else:
    index = -1

或者,作为生成器表达式:

index = next((i for i, item in enumerate(my_list) if item.id == 'specific_id'), -1)

关于python - 在 Python 中按属性获取对象列表中的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19162285/

相关文章:

php - 如何使用 PHP/MySQL 计算和使用 Morton (z-index) 值来索引地理数据?

Python Google Analytics OAuth 服务帐户和 2LO; "sub"参数和域范围委托(delegate)

python - 以其他维度的关联值为条件对 3d numpy 数组的分配进行矢量化

azure - 我想在cosmos db中添加索引

java - hibernate 查询列表 : empty or null?

c# - 如何在 MySql 数据库中存储 List<string>

mongodb - 在 mongodb 中,为什么查询索引子文档数组比索引一级文档更快?

python - 使用带有附加参数的 python 运行程序

python - 如何在 pyspark 中将 Dataframe 转换为 RDD?

python - 使用 Python Pandas 检查某个项目是否先前出现在项目列表中