Reputation: 23
I have a list like this:
[('TIPE_ORG', 'Corea'), ('TIPE_ORG', 'United Kingdom'), ('TIPE_ORG', 'Russia'), ('TIPE_ORG', 'Germany'),('TIPE_PER', 'Pepe Martínez')]
I want it to be sorted by text length from largest to smallest of the second parameter Let it be like this:
[('TIPE_ORG', 'United Kingdom'),('TIPE_PER', 'Pepe Martínez'), ('TIPE_ORG', 'Germany'), ('TIPE_ORG', 'Russia'),('TIPE_ORG', 'Corea')]
I have tried to do this, but having two parameters does not order it for the second, but for the first TIPE_ORG:
x.sort(key=len, reverse=True)
Upvotes: 0
Views: 197
Reputation: 2930
this can be done by sorting inplace with sort
method or sorting and return anew sorted list with sorted
method. for the equality
decition, we use lambda
function. see below:
my_list=[('TIPE_ORG', 'Corea'), ('TIPE_ORG', 'United Kingdom'),('TIPE_PER', 'Pepe Martínez')]
my_new_list = sorted(my_list, key=lambda this_tup:len(this_tup[1]), reverse=True)
or
sort(my_list, key=lambda this_tup:len(this_tup[1]), reverse=True)
you can refer to this link they have good examples about lambda expressions
and how to use it.
Upvotes: 2
Reputation: 300
You can use sorted
method with a lambda function as below.
lst=[('TIPE_ORG', 'Corea'), ('TIPE_ORG', 'United Kingdom'), ('TIPE_ORG', 'Russia'), ('TIPE_ORG', 'Germany'),('TIPE_PER', 'Pepe Martínez')]
sorted(lst,key=lambda key:len((key[1])),reverse=True)
Output will be
[('TIPE_ORG', 'United Kingdom'),
('TIPE_PER', 'Pepe Martínez'),
('TIPE_ORG', 'Germany'),
('TIPE_ORG', 'Russia'),
('TIPE_ORG', 'Corea')]
Upvotes: 2