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

  • Variable names should be descriptive. Instead of `list1`, why not `names`? And instead of `list2`, why not `marks`? – mhlester Apr 24 '14 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(...` – Kevin Apr 24 '14 at 16:59
  • possible duplicate of [How can I "zip sort" parallel numpy arrays?](http://stackoverflow.com/questions/1903462/how-can-i-zip-sort-parallel-numpy-arrays) – JasonMArcher Apr 24 '14 at 17:15

1 Answers1

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)]
falsetru
  • 357,413
  • 63
  • 732
  • 636