简体   繁体   中英

sorting list of list in python

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

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM