Python sort order of lists in a multidimensional array

I would like to rotate this data in Python (sorted alphabetically):

test = [['ma', 'e', 'wa', 'ka'], ['ma', 'haa', 'laa'], ['ma', 'ka', 'm', 'haa', 'laa', 'ca', 'j', 'ra'], ['ma', 'ra'], 'ma']

In a multidimensional array with its elements , sorted by the number of elements in each list , like this:

test = ['ma', ['ma', 'ra'], ['ma', 'haa', 'laa'], ['ma', 'e', 'wa', 'ka'], ['ma', 'ka', 'm', 'haa', 'laa', 'ca', 'j', 'ra']]

If you just looked at the length, I would like it to go from [4, 3, 8, 2, 1] to [1, 2, 3, 4, 8], but I don't necessarily want the solution to be specific for this example.

+4
source share
2 answers
test = sorted(test, key=lambda x: len(x) if type(x)==list else 1)

I tried:

>>> test = [['ma', 'e', 'wa', 'ka'], ['ma', 'haa', 'laa'], ['ma', 'ka', 'm', 'haa', 'laa', 'ca', 'j', 'ra'], ['ma', 'ra'], 'ma']
>>> test = sorted(test, key=lambda x: len(x) if type(x)==list else 1)
>>> test
['ma', ['ma', 'ra'], ['ma', 'haa', 'laa'], ['ma', 'e', 'wa', 'ka'], ['ma', 'ka', 'm', 'haa', 'laa', 'ca', 'j', 'ra']]

, - , , , type (x) == list else 1

+4

:

sorted(test, key=lambda x: isinstance(x,list) and len(x) or 1)
+1

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


All Articles