在python排序元组列表?
你如何排序元组的列表由elemant多数民众赞成? 下面说一下是列表LL。 欲ID2排序 - LL [1],这是一个元组为递增。 我该怎么做。在python排序元组列表?
Id, Id2 CCC
A123 A120 '2011-03'
LL= A133 A123 '2011-03'
D123 D120 '2011-04'
D140 D123 '2011-04'
看一看http://wiki.python.org/moin/HowTo/Sorting/
sorted(LL, key=itemgetter(1))
可能会做你想要什么。
请注意,您必须from operator import itemgetter
得到itemgetter
功能。
In [1]: LL = (('A123', 'A120', '2011-03'), ('A133', 'A123', '2011-03'), ('D123', 'D120', '2011-04'), ('D140', 'D123', '2011-04'))
In [2]: from operator import itemgetter
In [3]: sorted(LL, key=itemgetter(1))
Out[3]:
[('A123', 'A120', '2011-03'),
('A133', 'A123', '2011-03'),
('D123', 'D120', '2011-04'),
('D140', 'D123', '2011-04')]
不要紧,该键= itemgetter(1)是一个元组 – Merlin 2011-04-24 20:54:47
'键= itemgetter(1)'将'排序()在'LL每个元素'取得与指数产品1 '。请实际读取我链接到页面,它解释它:http://wiki.python.org/moin/HowTo/Sorting/#Operator_Module_Functions – ThiefMaster 2011-04-24 20:57:52
我一直在试图找出这个了一会儿。我找到了我的概率。数据库具有排序列作为主键,不断更改我的订单。 ;-)))))!谢谢 – Merlin 2011-04-24 21:17:03
你可以去:
LL.sort(key=lambda x:x[1])
其中1是元组的元素的索引。
更好地使用'operator'模块中的'itemgetter(1)'。否则,需要为每个项目调用一个python函数(如果使用默认的CPython实现,那么'operator'函数就用C编写) – ThiefMaster 2011-04-24 20:58:46
'ID2 - LL [1],这是一个元组作为asc' - * *什么? – ThiefMaster 2011-04-24 20:54:12
我通过ID2要排序,ASC – Merlin 2011-04-24 20:57:14