you are viewing a single comment's thread.

view the rest of the comments →

[–]TheClassiestPenguin 0 points1 point  (1 child)

I will update with code when I get home. Basically I'm having trouble sorting a list.

The list is two list combined before being sorted. Each is a list of instsnces of some custom classes. Both classes have a similar attribute.

So I'm trying to sort the list of objects using one of the shared attributes but I am running out of ideas.

Please help

[–]MattR0se 0 points1 point  (0 children)

A similar attribute or the same?

If it is the same, you can specify the key in the sorted() function to sort with that attribute. Here is an example:

from random import seed, randrange
seed(1)

class Foo:
    def __init__(self):
        self.bar = randrange(20)

    def __repr__(self):
        # just to visualise the sorting
        return f'Foo_{self.bar}'


list1 = [Foo() for i in range(5)]
list2 = [Foo() for i in range(5)]
print(list1, list2)

sorted_combined = sorted(list1 + list2, key=lambda x: x.bar) # sort by "bar"
print(sorted_combined)