[Tutor] sorting data from multiple arrays

Jeff Peery jeffpeery at yahoo.com
Thu Mar 22 21:00:10 CET 2007


Thanks for all the responses, that is a huge help!

Jeff

Kent Johnson <kent37 at tds.net> wrote: Jeff Peery wrote:
> hello, I typically run into this problem and I'm not always sure of the 
> most efficient way to handle it. I often work with multiple arrays of 
> data, say arrays a, b, and c, and I want to sort the elements of b and c 
> based on a. for example:
> 
> a = [3,2,1,4]
> b = ['hi', 'my','name', 'is']
> c = [5,2,4,2]
> 
> I order 'a' from small to large and do the same rearrangement to 'b' and 
> 'c':
> a = [1,2,3,4]
> b = ['name', 'my','hi', 'is']
> c = [4,2,5,2]
> 
> usually I do some terrible looking for loops and iterate over the whole 
> mess.... is there a clean, efficient way to do this, or is there a nice 
> function that would reorder the elements of b and c based on the soring 
> of a?

Decorate-sort-undecorate 
(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52234)
to the rescue:

In [12]: a = [3,2,1,4]
In [13]: b = ['hi', 'my','name', 'is']
In [14]: c = [5,2,4,2]
In [15]: temp = zip(a, b, c)
In [16]: temp
Out[16]: [(3, 'hi', 5), (2, 'my', 2), (1, 'name', 4), (4, 'is', 2)]
In [17]: temp.sort()
In [18]: _, b, c = zip(*temp)
In [19]: b
Out[19]: ('name', 'my', 'hi', 'is')
In [20]: c
Out[20]: (4, 2, 5, 2)

Or, if you are a fan of one-liners:
In [21]: _, b, c = zip(*sorted(zip(a, b, c)))

Methinks there should be a clever way to do this with the key= argument 
to sort, but I can't think of it at the moment...

Kent


 
---------------------------------
Finding fabulous fares is fun.
Let Yahoo! FareChase search your favorite travel sites to find flight and hotel bargains.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070322/7124dd6c/attachment.html 


More information about the Tutor mailing list