0

I have a file [ Name Age Marks] . I have stored each values of Name in a list1 . Marks in list2. I have combined both lists using zip function in python:

 list3 =[]
 list3 = zip(list1,list2)

Eg: list3 = ((Steve,32),(David,65),(Ram,43),(Mary,87)) Now I want to sort list3 in descending order of marks. So kindly help how to proceed with this. I am new to python. Thanks for your time and consideration. Awaiting response

3
  • Variable names should be descriptive. Instead of list1, why not names? And instead of list2, why not marks? Commented Apr 24, 2014 at 16:54
  • You don't need to do list3 =[] before assigning it to zip, by the way. I'm guessing you're doing it in order to "declare" that list3 is a list. But in Python, variables do not need declaration; you could have done list3 = 2342 instead, and everything would still work the same way. So you may as well not put anything before list3 = zip(... Commented Apr 24, 2014 at 16:59
  • possible duplicate of How can I "zip sort" parallel numpy arrays? Commented Apr 24, 2014 at 17:15

1 Answer 1

2

sorted, list.sort accept optional key function. Return values of the function are used for comparison.

>>> list3 = [('Steve',32),('David',65),('Ram',43),('Mary',87)]
>>> sorted(list3, key=lambda item: item[1])
[('Steve', 32), ('Ram', 43), ('David', 65), ('Mary', 87)]

>>> sorted(list3, key=lambda item: -item[1]) # negate the return value.
[('Mary', 87), ('David', 65), ('Ram', 43), ('Steve', 32)]

>>> sorted(list3, key=lambda item: item[1], reverse=True) # using `reverse`
[('Mary', 87), ('David', 65), ('Ram', 43), ('Steve', 32)]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it worked. I would like to know if I have a list :

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.