0

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)
Adam
  • 2,820
  • 1
  • 13
  • 33
María
  • 23
  • 4
  • Does this answer your question? https://stackoverflow.com/questions/3121979/how-to-sort-a-list-tuple-of-lists-tuples-by-the-element-at-a-given-index – Ronald Jul 08 '20 at 10:17
  • But lambda is for ordering numbers, right? – María Jul 08 '20 at 10:21
  • @lamda can do evrey thing you till it to do. see my answer. – Adam Jul 08 '20 at 10:24
  • `key=callback_function`. lambda is an anonymous function. Here you can learn about lambda functions: https://realpython.com/python-lambda/ – Ronald Jul 08 '20 at 10:24
  • Does this answer your question? [How to sort a list/tuple of lists/tuples by the element at a given index?](https://stackoverflow.com/questions/3121979/how-to-sort-a-list-tuple-of-lists-tuples-by-the-element-at-a-given-index) – Daniel Morell Jul 08 '20 at 10:51

2 Answers2

2

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

Adam
  • 2,820
  • 1
  • 13
  • 33
  • Apart from the fact that this answer sorts alphabetically and not on length, it is discouraged to provide an answer if the question already has an answer elsewhere. – Ronald Jul 08 '20 at 10:26
  • i am fixing my answer. patience please. i dont know what you talking about @Ronald. now you can remove the down vote. – Adam Jul 08 '20 at 10:30
2

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')]
Bimarsha Khanal
  • 300
  • 2
  • 14