Python 3.3使用多个键对元组列表进行排序 [英] Python 3.3 Sorting a tuple list with multiple keys

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

问题描述

我有一个问题(在欧拉计划问题中遇到),因为我有一个元组列表的列表,例如.

I'm having a bit of a problem (encountered during a Project Euler problem) in that I have a list of lists of tuples e.g.

  [...
    [(-119, 359), (668, -609), (-358, -494)], 
    [(440, 929), (968, 214), (760, -857)], 
    [(-700, 785), (838, 29), (-216, 411)], 
    [(-770, -458), (-325, -53), (-505, 633)],
  ...] 

我想做的是按照具有最小第一个值的元组对它们进行排序,但是如果它们相等,则比较第二个值并按最小的顺序对其进行排序.我一直在寻找,似乎无法找到一种方法来做到这一点.我发现的唯一东西是旧的python 2.x版本,该版本在给定cmp参数的地方进行了排序.

What I want to do is sort them by the tuple with the smallest first value, but if they are equal to then compare the second values and order by the smallest of these. I've been looking about and can't seem to find a way to do this. The only thing I have found is the old python 2.x version of sorted where it is given a cmp argument.

任何帮助将不胜感激,

此致

Ybrad

我刚刚意识到上面的措词有点不正确.我想做的是对每个子列表中的元组进行排序,而不是整个列表中的元组.

I just realised the above is worded slightly incorrectly. What I want to do is sort the tuples within each sub-list, not the list of lists as a whole.

推荐答案

您可以很容易地做到这一点:

You can very easily do that as:

a = [sorted(i) for i in a]

>>> print a
[[(-358, -494), (-119, 359), (668, -609)],
 [(440, 929), (760, -857), (968, 214)],
 [(-700, 785), (-216, 411), (838, 29)],
 [(-770, -458), (-505, 633), (-325, -53)]]

对于第二个请求,您可以按照以下步骤进行操作:

For your second request, you can do it as:

a = [sorted(i, key=lambda i: (i[0], -i[1])) for i in a]

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

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