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')]
1

2 Answers 2

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')]
>>> 
Sign up to request clarification or add additional context in comments.

2 Comments

if i need to sort like this means [('abc', '23'),('sugan', '12'),('ghi', '11'),('shankar', '10')]
if you want it in descending order just use sorted(l, key=lambda x: int(x[1]), reverse=True)
0

Try this to sort

sorted(yourList, key=lambda tupVal: float(tupVal[1]))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.