如何在多个条件下对python进行排序? [英] How to sort in python with multiple conditions?

查看:91
本文介绍了如何在多个条件下对python进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含子列表的列表,如下所示:

I have a list with sublists as follows:

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

我想用三个条件对它进行排序: 首先,按子列表索引2中的最高整数,然后按子列表索引1中的单词长度,最后按子列表第1个索引中的字母顺序.

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.

感谢您的帮助.谢谢.

推荐答案

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

every element is a list of 2 elements, sorting by the length of the list is useless because all of them has the same length, maybe you want to sort by the length of the first element so

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

这篇关于如何在多个条件下对python进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆