简体   繁体   English

如何制作一个返回元组列表的函数,该列表按元组中的最后一个元素排序?

[英]How do I make a function that returns a list of tuples sorted by the last element in the tuple?

This is the code I am trying to run but it doesn't work. 这是我尝试运行的代码,但是它不起作用。 It says invalid syntax. 它说无效的语法。

    def sort_last(tuples):
        return sorted(tuples, key = tuples[-1]


    x = [(7, 6), (5, 5), (2, 1)]
    print sort_last(x)

Use a lambda: 使用lambda:

def sort_last(tuples):
    return sorted(tuples, key = lambda t: t[-1])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在元组列表中索引元组的最后一个元素 - how to index the last element of a tuple in a list of tuples 给定一个元组列表,如果第一个元素相同,我如何在每个相似的元组中添加第二个元素 - Given a list of tuples, if the first element is the same, how do i add the second element inside each similar tuple 如何获取 2 列中的列表并创建一个元组,将所有元组放入一个列表中,然后返回该列表? - How do I take a list that is in 2 columns and make a tuple, put all the tuples in a list, and return that list? 我如何从 dict 值和元组列表中获取每个元素并从中生成一个元组 - How i can get every element from dict value and list of tuples and make one tuple from it 如何“截断”相同长度的元组的最后一列? - How do I “truncate” the last column of a tuple of same length tuples? 如何从嵌套的元组列表中获取每个元组的第一个元素? - How do I get the first element of every tuple from a nested list of tuples? 如何将元组转换为元组元组? - How do I turn a tuple into a tuple of tuples? 如何使用元组列表中的元组中的值作为函数的参数? - How do I use values from a tuple which is in a list of tuples as arguments for a function? 如何将元组元组转换为一行列表(pythonic)? - How do I convert tuple of tuples to list in one line (pythonic)? 如何基于第一个值Python替换元组排序列表中的元组 - How to replace a tuple in sorted list of tuples basing on first value Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM