簡體   English   中英

按屬性值排序對象列表,屬性值的順序在另一個列表中

[英]sorting list of objects by attribute values, order of attribute values are in another list

a = ['123b4', '234v5', 'lobf56']
b = [obj1, obj2, obj3] # where each obj is list of object which has attribute called 'serial' which matches serial numbers in list #a

其中 obj1.serial 是 234v5,obj2.serial 是 lobf56,obj3.serial 是 123b4

tmplist=list()
for each in a:
    for obj in b:
        if each == obj.serial:
            tmplist.append(obj)

print(tmplist)

輸出:[obj3, obj1, obj2]

我目前能夠以上述方式實現排序。 但是有沒有更好的方法來做到這一點?

列表理解有幫助嗎?

[obj for each in a for obj in b if each == obj.serial]

如果你比較兩者之間的時間,你的方法是:

1.6 µs ± 25.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

列表理解需要:

1.37 µs ± 18.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

因此,如果說“更好的方法”,您的意思是效率。 這肯定很重要。

暫無
暫無

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

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