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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19162285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:02:25  来源:igfitidea点击:

Get index in the list of objects by attribute in Python

pythonlistindexing

提问by sebaszw

I have list of objects with attribute id and I want to find index of object with specific id. I wrote something like this:

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

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?

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

采纳答案by Abhishek

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:

对于多次出现,根据下面 Azam 的评论:

[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

Edit1:对于每个评论其对象列表的人,您只需要访问 id

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

回答by Daniel Roseman

You can use enumerate:

您可以使用enumerate

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

回答by Joel Cornett

Use enumeratewhen you want both the values and indices in a forloop:

使用enumerate时,你在想这两个值和指数for环:

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)

回答by chepner

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.

这是一个不使用(显式)循环的替代方法,有两种不同的方法可以从原始列表中生成“id”值列表。

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