简体   繁体   中英

How to sort in python with multiple conditions?

I have a list with sublists as follows:

result = [ ['helo', 10], ['bye', 50], ['yeah', 5], ['candy',30] ]

I want to sort this with three conditions: first, by highrest integer in index 2 of sublist, then by length of word in index 1 of sublist, and finally by alphabetical order in the 1st index of sublist.

I tried to do the following but it does not work:

finalresult = sorted(result, key=lambda word: (-word[1], len(word), word[0]))

This sorts it by the highest integer and alphabet order but not by length of word.

Any help is appreciated. Thank You.

每个元素都是2个元素的列表,按列表的长度排序是没用的,因为它们都具有相同的长度,也许你想按第一个元素的长度排序所以

finalresult = sorted(result, key=lambda word: (-word[1], len(word[0]), word[0]))

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