简体   繁体   中英

How to sort a list of lists based on the length of the inner lists, but if two inner lists are equal then sort based on first element of inner list

I am looking for a way to be able to sort a list of lists based on the length of the inner lists, but if two inner lists are equal then sort based on first element of inner list.

I have seen several clean non-verbose solutions for how to do it when you need to sort lists of lists based on the length of the inner lists, but they don't take into consideration how to sort the list when there are two inner lists of equal length such as this one which uses the following method:

a.sort(key=len)

If there two inner lists of equal length then I need to sort the two inner lists by the value of the first element of the inner list (which is guaranteed to be unique in all of the lists based on the input conditions)

For example: if I have the following list of lists

[[1, 2, 3], [2, 1], [3, 2], [4, 5, 1], [5]]

then I would need it to be sorted into the following list of lists:

[[4, 5, 1], [1, 2, 3], [3, 2], [2, 1], [5]]

you can define rule in key in sort function on the order of sorting

l =[[1, 2, 3], [2, 1], [3, 2], [4, 5, 1], [5]]
l.sort(key=lambda x:[len(x), x[0]], reverse=True)
print(l)

output

[[4, 5, 1], [1, 2, 3], [3, 2], [2, 1], [5]]

Using a tuple as key in the sort function allows for a hierarchical sorting priority. When the ordering of key parts is not all ascending or all descending, you have two options:

(1) perform multiple sorts leveraging the fact that Python's sort is stable: Ie sort by the lowest priority key part then again on the higher priority part

a.sort(key=lambda v:v[0],reverse=True) 
a.sort(key=len)                # ascending length, descending 1st value

or

a.sort(key=lambda v:v[0])             
a.sort(key=len,reverse=True)   # descending length, ascending 1st value

(2) if your key parts are numeric, use the inverse (negative) value in the tuple

a.sort(key = lambda v:(len(v),-v[0]))  # ascending length, descenging 1st value 

or

a.sort(key = lambda v:(-len(v),v[0]))  # descending length, ascending 1st value

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