在Python中按属性获取对象列表中的索引 [英] Get index in the list of objects by attribute in Python
本文介绍了在Python中按属性获取对象列表中的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有具有属性ID的对象列表,并且我想查找具有特定ID的对象的索引.我写了这样的东西:
I have list of objects with attribute id and I want to find index of object with specific id. I wrote something like this:
index = -1
for i in range(len(my_list)):
if my_list[i].id == 'specific_id'
index = i
break
但是看起来不太好.有更好的选择吗?
but it doesn't look very well. Are there any better options?
推荐答案
如果要在 for
循环中使用值和索引,请使用枚举
:
Use enumerate
when you want both the values and indices in a for
loop:
for index, item in enumerate(my_list):
if item.id == 'specific_id':
break
else:
index = -1
或者,作为生成器表达式:
Or, as a generator expression:
index = next((i for i, item in enumerate(my_list) if item.id == 'specific_id'), -1)
这篇关于在Python中按属性获取对象列表中的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文