简体   繁体   English

排序python中的列表列表

[英]sorting list of list in python

I have a list in python like - 我在python中有一个列表 -

[['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) . 因此,我们将自定义函数传递给外部排序函数lambda x: (len(x), x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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