444,050 Members | 1,009 Online
Need help? Post your question and get tips & solutions from a community of 444,050 IT Pros & Developers. It's quick & easy.

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

 P: 6 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. Jul 31 '11 #1

Following are a couple of ways:
Expand|Select|Wrap|Line Numbers
1. >>> names = ["Bill", "Jane", "Harrold", "Nancy"]
2. >>> courses_passed = [12, 6, 14, 19]
3. >>> names = ["Bill", "Jane", "Harold", "Nancy"]
4. >>> courses_passed = [12, 6, 14, 19]
5. >>> combined = zip(names, courses_passed)
6. >>> combined
7. [('Bill', 12), ('Jane', 6), ('Harold', 14), ('Nancy', 19)]
8. >>> combined.sort(lambda x,y: cmp(x[1], -y[1]))
9. >>> combined
10. [('Nancy', 19), ('Harold', 14), ('Bill', 12), ('Jane', 6)]
11. >>> print "%s passed %s courses" % (combined[0])
12. Nancy passed 19 courses
13. >>> most = max(courses_passed)
14. >>> names[courses_passed.index(most)]
15. 'Nancy'
16. >>>