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)
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.
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')]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.