1

I have list of tuple values. I need to sort value by id from the tuple list. Can anyone help me to do this.

  l = [('abc','23'),('ghi','11'),('sugan','12'),('shankar','10')]

I need a output like this.

  l = [('shankar','10'),('ghi','11'),('sugan','12'),('abc','23')]

and also if i need to sort like this means

  l =  [('abc', '23'),('sugan', '12'),('ghi', '11'),('shankar', '10')]
Python Team
  • 1,143
  • 4
  • 21
  • 50
  • 2
    There is a similar answer here (like Avinash Raj gave it): [https://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples](https://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples) – rocksteady Nov 16 '15 at 08:48

2 Answers2

6

You may pass key param to sorted function.

>>> l = [('abc','23'),('ghi','11'),('sugan','12'),('shankar','10')]
>>> sorted(l, key=lambda x: int(x[1]))
[('shankar', '10'), ('ghi', '11'), ('sugan', '12'), ('abc', '23')]
>>> 
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

Try this to sort

sorted(yourList, key=lambda tupVal: float(tupVal[1]))
Mangu Singh Rajpurohit
  • 10,806
  • 4
  • 68
  • 97