be_good_do_good
be_good_do_good

Reputation: 4441

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

Where obj1.serial is 234v5, obj2.serial is lobf56 and obj3.serial is 123b4

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

print(tmplist)

output: [obj3, obj1, obj2]

I am currently able to achieve the sorting in above manner. But is there a better way to do it?

Upvotes: 2

Views: 49

Answers (1)

lmiguelvargasf
lmiguelvargasf

Reputation: 70003

Does a list comprehension helps?

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

If you compare the time between both, your approach takes:

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

The list comprehension takes:

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

Therefore, if by "a better way to do it" you mean efficiency. This definitely counts.

Upvotes: 1

Related Questions