views:

170

answers:

3

I have 3 lists, each with equal elements: email addresses, salaries and IDs

I'd like to sort the email addresses alphabetically and in some way sort the other 2 lists (salaries and IDs).

E.g.,
Emails:
[email protected]
[email protected]

Salaries:
50000
60000

IDs:
2
1

The puzzle: I'd like to sort Emails such that [email protected] is first and [email protected] is last and Salaries is 60000 then 50000 and IDs is 1 then 2.

Additional detail:
1. Length of lists are the same and can be longer than two elements.
2. I will subsequently pass IDs to functions to retrieve further lists. Those lists won't need sorting as they will adopt the order of the IDs list.

+4  A: 

Try:

emails = ["[email protected]", "[email protected]"]
salaries = [50, 60]
ids = [2, 1]

intermediate = zip(emails, salaries, ids)
intermediate.sort()

result = zip(*intermediate)
ebo
A: 

Assuming that each email ID is unique, then this will work:

sortedEmails = emails[:]
sortedEmails.sort()

sortedSalaries = []
for email in sortedEmails:
    i = emails.index(email)
    sortedSalaries.append(salaries[i])

Hope that helps

inspectorG4dget
-1 O(N**2) because list.index is O(N)
John Machin
+2  A: 

This is essentially ebo's solution, made to a one-liner with the user of sorted() rather than list.sort, and multiple lvalues in the assignement to get the individual list (named as the original but with an s_ prefix) directly.

>>> email = ['[email protected]', '[email protected]']
>>> salaries = [50000, 60000]
>>> ids = [2,1]

>>> s_email, s_salaries, s_ids = zip(*sorted(zip(email, salaries, ids)))

>>> s_email
('[email protected]', '[email protected]')
>>> s_salaries
(60000, 50000)
>>> s_ids
(1, 2)
>>>
mjv