在python中对具有3个元素的元组列表进行排序 [英] Sorting a list of tuples with 3 elements in python

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

问题描述

我有一些元组的列表.每个元组都有三个元素.我需要对列表进行排序.为了打破两个元组之间的关系,先查看元组的第一个元素,然后如果仍然绑定,则查看第二个元素.列表如下.

I have a list of some tuples. Each tuple has three elements. I need to sort the list. To break tie between two tuples, first element of tuple is looked then if still tied then the second element. List is like below.

L = [(1, 14, 0), (14, 1, 1), (1, 14, 2), (14, 2, 3), (2, 4, 4), (4, 11, 5), (11, -1000, 6)]

在C语言中,sort函数具有一个compare函数,它可以简单地完成所有操作.但是有时在python中尝试后我无法弄清楚.有人可以帮我吗?

In C the sort function takes a compare function and that does everything simply. But I couldn't figure it out after trying for sometimes in python. Can anybody help me?

推荐答案

只需对列表进行排序;默认的排序方式可以满足您的需求.

Just sort the list; the default sort does just what you want.

比较两个元组时,将根据它们的内容对其进行排序;首先,它们在第一个元素上排序,如果相等,则在第二个元素上排序,依此类推.

When comparing two tuples, they are ordered according to their contents; sorted on the first element first, then if they are equal, sorted on the second element, etc.

演示:

>>> L = [(14, 2, 3), (1, 14, 0), (14, 1, 1), (1, 14, 2), (2, 4, 4), (4, 11, 5), (11, -1000, 6)]
>>> sorted(L)
[(1, 14, 0), (1, 14, 2), (2, 4, 4), (4, 11, 5), (11, -1000, 6), (14, 1, 1), (14, 2, 3)]

我将(14, 2, 3)元素向前移动以显示它仍在(14, 1, 1)之后排序.

I moved the (14, 2, 3) element forward to show that it is still sorted after (14, 1, 1).

Python的list.sort()方法和sorted()函数采用一个key函数,如果需要其他排序顺序,该函数将返回一个对其进行排序的值.例如,如果您要首先对最后一个元素进行排序,然后再对第二个元素进行排序,依此类推,则可以使用:

Python's list.sort() method and sorted() function take a key function that returns a value on which to sort instead if you need a different sort order. If you wanted to sort on the last element first, then second last, etc. for example, you'd use:

sorted(L, key=lambda t: t[::-1])

其中,lambda返回一个反向元组以进行排序.传递给key的可调用对象将针对输入序列中的每个元素进行调用,以在排序之前扩充"列表,就像您已经做过的一样:

where the lambda returns a reversed tuple to sort on instead. The callable object you pass to key is called for each element in the input sequence to 'augment' the list before sorting, as if you had done:

[s[1] for s in sorted((key(s), s) for s in L)]

t[::-1]使用反转片.

有关更多详细信息,请参见 Python排序方法.

For more detail, see the Python Sorting HOWTO.

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

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