Reputation: 25639
How do you sort a list by elemant thats a tuple? Let say below is the list LL. I want to sort ID2 -- LL[1] which is a tuple as asc. How would I do it.
Id, Id2 CCC
A123 A120 '2011-03'
LL= A133 A123 '2011-03'
D123 D120 '2011-04'
D140 D123 '2011-04'
Upvotes: 0
Views: 1021
Reputation: 318508
Have a look at http://wiki.python.org/moin/HowTo/Sorting/
sorted(LL, key=itemgetter(1))
might do what you want.
Please note that you have to from operator import itemgetter
to get the itemgetter
function.
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')]
Upvotes: 4
Reputation: 1810
You can go for:
LL.sort(key=lambda x:x[1])
Where 1 is the index of the element of the tupple.
Upvotes: 0