How can I sort 2 parallel lists in the same way?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Borden
    New Member
    • Jul 2011
    • 6

    How can I sort 2 parallel lists in the same way?

    Ok,so I have 2 lists with the same lenght.The one has etc. names of students and the other has how many courses a student has passed and these lists ara parallel.I want to sort out the second list so I can find the most courses passed by a student,but how can the first list be sorted in the same way so the right student is shown?Can I use the "sort" method in some way or I have to do a whole different proccess?

    Thank you in advance.
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Following are a couple of ways:
    Code:
    >>> names = ["Bill", "Jane", "Harrold", "Nancy"]
    >>> courses_passed = [12, 6, 14, 19]
    >>> names = ["Bill", "Jane", "Harold", "Nancy"]
    >>> courses_passed = [12, 6, 14, 19]
    >>> combined = zip(names, courses_passed)
    >>> combined
    [('Bill', 12), ('Jane', 6), ('Harold', 14), ('Nancy', 19)]
    >>> combined.sort(lambda x,y: cmp(x[1], -y[1]))
    >>> combined
    [('Nancy', 19), ('Harold', 14), ('Bill', 12), ('Jane', 6)]
    >>> print "%s passed %s courses" % (combined[0])
    Nancy passed 19 courses
    >>> most = max(courses_passed)
    >>> names[courses_passed.index(most)]
    'Nancy'
    >>>

    Comment

    • Borden
      New Member
      • Jul 2011
      • 6

      #3
      Thanks,that was perfect!

      Comment

      Working...