简体   繁体   中英

python sort list of lists with tie-breaker

What is the most pythonic way to sort a list of lists with a tie-breaker?

I can sort by sub-list length (longest to shortest):

>>> l = [['c'], ['a', 'b'], ['b', 'c'], ['a', 'b', 'c']]

>>> list(reversed(sorted(l, key=len)))
[['a', 'b', 'c'], ['b', 'c'], ['a', 'b'], ['c']]

But I want to preserve order when the lengths are equal, so the output I want is:

[['a', 'b', 'c'], ['a', 'b'], ['b', 'c'], ['c']]

Timsort (Python's built-in sorting algorithm) is stable, meaning it keeps the original order of elements with equal keys. However, you reversed the original order by using the reversed function.

If you want to reverse the resulting list and preserve the original order of elements comparing equal, use reverse=True :

In [3]: sorted(l, key=len, reverse=True)
Out[3]: [['a', 'b', 'c'], ['a', 'b'], ['b', 'c'], ['c']]

您可以创建一个新列表,将每个元素及其在原始列表中的位置进行解析,然后使用该值作为键的次要部分进行排序,最后剥离出最终结果的位置。

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