user1998665
user1998665

Reputation: 81

Custom Python Sort: Double Precedence

I want to make a custom sort for my Python code that uses the built in sort() function, but can sort a list based on two values. The list I want sorted is structured as a list of tuples, which each contain 2 integers. What I want to sort to do is sort the list of tuples based on each of their first integers, but if two first integers are tied, it refers to their second integer, which is unique and therefore will not be the same. I want to use the speed of the built in sort() function, but be able to sort in this way. Any and all help is GREATLY APPRECIATED!

Upvotes: 0

Views: 179

Answers (2)

holdenweb
holdenweb

Reputation: 37113

You have just described the exact behavior of the list.sort() method, so once you have the tuples in a list, simply call the list's sort method (l.sort) with no arguments and it will be put in the desired order.

When more complex sorts are required you can pass a "key function" as a named argument, key. The function is applied to each element of the list to generate a sort key, then the elements are sorted in the order of their sort keys.

The sorted built-in function is convenient when you require a sorted copy of a list - it simply saves you the trouble of creating a copy then calling its sort method.

Upvotes: 0

yurisich
yurisich

Reputation: 7119

Built in sorted does this.

>>> l = [(1, 1), (1, 2), (2, 5), (2, 4)]
>>> sorted(l)
[(1, 1), (1, 2), (2, 4), (2, 5)]

The difference between sort() and sorted() is that sort() modifies the given list (and therefore, any other lists that are sharing its structure), while sorted() accepts an iterable, and returns a brand new list object.

For instance:

>>> a = list("alphabet")
>>> a
['a', 'l', 'p', 'h', 'a', 'b', 'e', 't']
>>> b = a
>>> b
['a', 'l', 'p', 'h', 'a', 'b', 'e', 't']
>>> b.sort()
>>> #this has modified the shared structure
>>> a
['a', 'a', 'b', 'e', 'h', 'l', 'p', 't']

As opposed to sorted()

>>> c = list("alphabet")
>>> d = c
>>> sorted(d)
['a', 'a', 'b', 'e', 'h', 'l', 'p', 't']
>>> c
['a', 'l', 'p', 'h', 'a', 'b', 'e', 't']

sorted() is safer.

Upvotes: 2

Related Questions