Lexicographically sort deeply nested lists of mixed data types in Python 3

In Python 3, the method list.sort()will perform a lexicographic look. But in Python 3, comparing a list with floator intcalls a TypeError, unlike Python 2, where you can do this:

>>> [0, 1] < 2
False

What is the best way to achieve old Python 2 behavior?

I tried subclassing list, but for this, each of the nested lists must be added to the type of the subclass so that all nested comparisons use overridden comparison methods. Is there a way to accomplish this that doesn't resort to recursively converting all nested lists to a subclass?

I would like to compare two lists:

>>> a = [[[0, 1], [2, 3]], [0, 1]]
>>> b = [[0, 1], [2, 3]]
>>> a < b
False

False, a[0][0] list, b[0][0] int, int , a list.

Edit:

, Python 3 list.sort, , list float int, list .

+4
3

Python 2:

, ; , , , .

, . , [0, 1] < 2, Python 3.

, [[[0, 1], [2, 3]], [0, 1]], :
[[0, 1], [2, 3]] and [0, 1]. python , , [0, 1] and [2, 3] 0 and 1 . [0, 1] with 0, , , , .

, .

, , , (- ), - False.

try:
    [0, 1] < 2
except TypeError:
    # return or assign False. True is not actually meaningful.

, list.sort()

try:
    x.sort()
except TypeError:
    pass    # Do nothing. Python would produce meaningless results, anyway.

( ), , . . , .

+1

list, key sort :

sorted(l, key=custom_key_function)

custom_key_function(list_element) , .

, , , , , - custom_key_function.

0

Here is the slow way.

To add order between disparate types Aand Bplace their instances in tuples:

a = [[[0, 1], [2, 3]], [0, 1]]
b = [[0, 1], [2, 3]]

def deep_annotate(item):
    if isinstance(item, list):
        return (1, [deep_annotate(i) for i in item])
    else:
        return (0, item)

deep_annotate(a) < deep_annotate(b)
#>>> False

deep_annotate(a) > deep_annotate(b)
#>>> True

Unfortunately, many of them are not shortcuts, which can be done by smart use cmp_to_key.

0
source

Source: https://habr.com/ru/post/1545115/


All Articles