7

I have a list in python like -

[['C'], ['B'], ['A'], ['C', 'B'], ['B', 'A'], ['A', 'C']]

I want to sort it like follows -

[['A'], ['B'], ['C'], ['A', 'B'], ['A', 'C'], ['B', 'C']]

1 Answer 1

11

First sort the individual items in the lists and then sort the sorted lists based on the length and then the actual elements itself, like this

>>> data = [['C'], ['B'], ['A'], ['C', 'B'], ['B', 'A'], ['A', 'C']]
>>> sorted((sorted(item) for item in data), key=lambda x: (len(x), x))
[['A'], ['B'], ['C'], ['A', 'B'], ['A', 'C'], ['B', 'C']]

This works because, list of strings will be sorted lexicographically, by default. In your case, when the internal lists are sorted, the outer lists are first sorted based on the length of the list and if they are the same then the actual elements of the string itself will be used for the comparison.


This can be understood step-by-step. The first individual elements sorting results in this

>>> [sorted(item) for item in data]
[['C'], ['B'], ['A'], ['B', 'C'], ['A', 'B'], ['A', 'C']]

Now, we need to sort this based on the length in ascending order first, and then the elements also should be sorted. So, we pass a custom function to the outer sorting function, lambda x: (len(x), x).

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

1 Comment

Superb! another trick under hat-- key specifies a function of oneargument that is used to extract a comparison key from each list element.

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.