María
María

Reputation: 23

How to sort a list of tuples, by the second tuple element?

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

Answers (2)

AdamF
AdamF

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.

lambda

Upvotes: 2

Bimarsha Khanal
Bimarsha Khanal

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

Related Questions