Get index in the list of objects by attribute in Python

亡梦爱人 提交于 2020-12-04 15:33:46

问题


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?


回答1:


Assuming

a = [1,2,3,4]
val = 3

Do

a.index(val) if val in a else -1

For multiple occurrence, as per Azam's comment below:

[i if val == x else -1 for i,x in enumerate(a)] 

Edit1: For everyone commenting that its List of object, all you need is, access the id

[i if val == x.id else -1 for i,x in enumerate(a)] 



回答2:


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)



回答3:


Here's an alternative that doesn't use an (explicit) loop, with two different approaches to generating the list of 'id' values from the original list.

try:
    # index = map(operator.attrgetter('id'), my_list).index('specific_id')
    index = [ x.id for x in my_list ].index('specific_id')
except ValueError:
    index = -1



回答4:


You can use enumerate:

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


来源:https://stackoverflow.com/questions/19162285/get-index-in-the-list-of-objects-by-attribute-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!