sorting "problem"

B

Bror Johansson

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
 
G

Gary Herron

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))

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




Gary Herron
 
M

Mike C. Fletcher

You can use the Numeric Python extensions for this if you've got a lot
of elements:
>>> from Numeric import *
>>> a array([8, 5, 1, 4, 3])
>>> b array([5, 2, 9, 8, 7])
>>> indices = argsort(a)
>>> indices array([2, 4, 3, 1, 0])
>>> c,d = take(a,indices),take(b,indices)
>>> c array([1, 3, 4, 5, 8])
>>> d
array([9, 7, 8, 2, 5])

Enjoy,
Mike

_______________________________________
Mike C. Fletcher
Designer, VR Plumber, Coder
http://members.rogers.com/mcfletch/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top