如何根据元组列表中的值对元组进行排序 [英] How to sort a tuple based on a value within the list of tuples

查看:58
本文介绍了如何根据元组列表中的值对元组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,我希望根据元组最后一个元素的值对元组进行排序.例如,我有一个如下所示的元组.

In python, I wish to sort tuples based on the value of their last element. For example, i have a tuple like the one below.

tuples = [(2,3),(5,7),(4,3,1),(6,3,5),(6,2),(8,9)]

排序后我希望采用这种格式.

which after sort I wish to be in this format.

tuples = [(4,3,1),(6,2),(2,3),(6,3,5),(5,7),(8,9)]

我该怎么做?

推荐答案

Povide list.sort 使用适当的键函数返回元组的最后一个元素:

Povide list.sort with an appropriate key function that returns the last element of a tuple:

tuples.sort(key=lambda x: x[-1])

这篇关于如何根据元组列表中的值对元组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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