Arbitrary but deterministic sort a list of incompatible types

Viewed 134

I have the following lists of pairs:

test1 = [["A", 1],["A", 4], ["D", "Yes"], ["G", 12], ["B", True], ["H", "No"], ["G", 54], ["Z", 412.41]]
test2 = [["D", "Yes"], ["B", True], ["Z", 412.41], ["A", 4], ["G", 12], ["A", 1], ["G", 54], ["H", "No"]]

I want to be able to sort each list into a deterministic order. I don't care about the precise order, but if I sort two identical lists, then I want them to end up in the same order.

I tried:

test1.sort(key=lambda x: x[1])
test2.sort(key=lambda x: x[1])

But I got the error:

TypeError: '<' not supported between instances of 'str' and 'int'

How can I consistently sort a list that contains elements of incompatible types, such as str, bool, int, float?

1 Answers

Here is a suggestion:

list_1.sort(key=lambda x: (repr(type(x[1])), x[1]))

print(list_1)
# [['B', True], ['Z', 412.41], ['A', 1], ['A', 4], ['G', 12], ['G', 54], ['H', 'No'], ['D', 'Yes']]

This will group together the elements which have the same type for their second element. The actual values of x[1] will only be compared when the types differ, so you won't have a TypeError: '<' not supported between instances of something and something else.

Note how 412.41 was isolated from the other numbers, because it is a float, whereas the other numbers are int.

Related