簡體   English   中英

"在Python中按屬性獲取對象列表中的索引"

[英]Get index in the list of objects by attribute in Python

我有屬性 id 的對象列表,我想找到具有特定 id 的對象的索引。 我寫了這樣的東西:

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

當你想要for<\/code>循環中的值和索引時使用enumerate<\/code> :

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

這是一個不使用(顯式)循環的替代方案,使用兩種不同的方法從原始列表生成“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

您可以使用enumerate

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

為你的類實現__eq__<\/code>方法

class MyCls:
   def __init__(self, id):
       self.id = id

   def __eq__(self, other):
       # comparing with str since you want to compare
       # your object with str

       if not isinstance(other, str):
           raise TypeError("MyCls can be compared only with str")
       if other == self.id:
           return True
       return False

假設

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

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

對於多次出現,根據以下 Azam 的評論:

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

Edit1:對於每個評論其對象列表的人,您所需要的只是訪問id

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM