sorting "problem"

Gary Herron gherron at islandtraining.com
Tue Nov 4 05:35:24 EST 2003


On Tuesday 04 November 2003 01:48 am, Bror Johansson wrote:
> Assume having defined two lists. There will be a one-to-one relationship
> between elements in the two lists.
>
> Is there a way to - when calling listA.sort() - have elements in listB
> shuffled the same as those in listA? When calling listB.sort(), the listA
> should be sorted alikewise.
>
> [I know how to circumvent the problem - e.g. by creating a temporary list
> with associated elements in tuples, sort this list and eventually extract
> the two separate lists.]
>
> Nevertheless, I'm curious whether it is possible - and if it is, how to -
> associate two - or more - lists with respect to sorting.
>
> /BJ

Here is a way to sort two (or more) associated lists for the price of
one sort.  No zipping and unzipping of the associated lists is
necessary.  One auxiliary list (of indexes) is used.

# Here are two associated lists
L1 = ('B', 'C', 'A')
L2 = ('b', 'c', 'a')

# A list of indexes (i.e., [0,1,2])
indexes = range(len(L1))

# Sort the indexes according values in L1
indexes.sort(lambda a,b: cmp(L1[a], L1[b]))

# Use the indexes to access either list in sorted order
print [L1[i] for i in indexes]     # prints ['A', 'B', 'C']
print [L2[i] for i in indexes]     # prints ['a', 'b', 'c']




Gary Herron







More information about the Python-list mailing list