Reputation: 4441
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
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