2
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?

1
  • 1
    I added an answer to your question. Commented Apr 6, 2019 at 1:35

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What code exactly did you time? I'm just curious because the gap is usually not that big.
@Tomothy32, you are right. I made the mistake of including the print statement. I just updated my answer. Great catch!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.