4

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.

2 Answers 2

5
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

Sign up to request clarification or add additional context in comments.

1 Comment

I recommend turning items that you mean as single lists and make them actual lists. You will avoid special handling scattered throughout your code as seen here. Additionally, it is what you mean.
1

One solution:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.