根据第一项对元组列表进行排序 [英] Sorting a list of tuples based on the first items

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

问题描述

如何根据第一个值对元组列表进行排序,即在字典中我们可以使用sorted(a.keys()).

How to sort a list of tuples based on the first value i.e, in a dictionary we can use sorted(a.keys()).

如何处理元组列表?

如果这些是元组值

t = [('2010-09-11', 'somedata', somedata),
     ('2010-06-11', 'somedata', somedata),
     ('2010-09-12', 'somedata', somedata)]

元组应根据第一个字段中的日期进行排序.

tuples should be sorted based on dates in the first field.

推荐答案

通常,只有sorted(t)起作用,因为元组通过字典顺序.如果您确实想忽略第一项之后的所有内容(而不是通过以下元素对具有相同第一个元素的元组进行排序),则可以提供一个key来挑选出第一个元素.最简单的方法是operator.itemgetter:

Usually, just sorted(t) works, as tuples are sorted by lexicographical order. If you really want to ignore everything after the first item (instead of sorting tuples with the same first element by the following elements), you can supply a key that picks out the first element. The simplest way would be operator.itemgetter:

import operator
...
for item in sorted(t, key=operator.itemgetter(0)):
    ...

当然,如果您想就地对列表进行排序,则可以使用t.sort(key=operator.itemgetter(0))代替.

Of course if you want to sort the list in-place, you can use t.sort(key=operator.itemgetter(0)) instead.

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

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