Sort order of lists in multidimensional array in Python

arrays, multidimensional-array, python, sorting

Solution

test = sorted(test, key=lambda x: len(x) if type(x)==list else 1)

I tried that:

>>> 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']]

the only odd thing is that not all elements in your original list are list, you included strings and list, that is why I had to add the condition if type(x)==list else 1

Problem

I would like to turn 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'] ``` Into a multidimensional array with its items sorted by the amount of items 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'd 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 to this example.

Original source