another way to sort like l.sort(key=lambda x:(x[0][0], -x[1][0]))

Peter Otten __peter__ at web.de
Wed Sep 8 10:08:30 CEST 2010


sajuptpm wrote:

> Now output is similar to first elements asc and second elements
> desc.But the problem is the -ve sign, i dont need that.
> 
> Have any other method to do it??

Sort twice:

>>> for item in items:
...     print item
...
('adams', 'anne')
('miller', 'arnold')
('miller', 'bill')
('adams', 'berta')
('adams', 'charlotte')
('miller', 'thomas')
>>> items.sort(key=lambda x: x[1], reverse=True)
>>> items.sort(key=lambda x: x[0])
>>> for item in items:
...     print item
...
('adams', 'charlotte')
('adams', 'berta')
('adams', 'anne')
('miller', 'thomas')
('miller', 'bill')
('miller', 'arnold')

See? First column ascending, second column descending within groups of rows 
with equal first column.

Peter



More information about the Python-list mailing list