sorting "problem"

Mel Wilson mwilson at the-wire.com
Tue Nov 4 10:16:01 EST 2003


In article <mailman.416.1067942139.702.python-list at python.org>,
Gary Herron <gherron at islandtraining.com> wrote:
>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.
[ code that inspired a followup ]

   Could the data be changed permanently?

L1 = [(d, rank) for rank, d in enumerate (L1)]
L1.sort()
# now L1[i][0] has original info and L1[i][1] has the connection to L2

   My own instinct is for zipping the lists together right
from the start, or associating them by dictionaries keyed on
the relevant common elements.. or generally.. writing code
that explicitely admits their relatedness.  (..I don't
like that wording..)  You won't have to stick them together
later if you've never broken them apart.

Maybe

L12 = zip (L1, L2)
L12.Sort()

Maybe you can dispense with L1 and L2 afterward, maybe not.
Memory cost will not be so bad, since lists, under the hood,
are arrays of references.

        Regards.        Mel.




More information about the Python-list mailing list