[Tutor] sorting data from multiple arrays
Kent Johnson
kent37 at tds.net
Fri Mar 23 11:27:26 CET 2007
Jeff Peery wrote:
> ... what is '*' in '*temp'? thanks!
Say you have a function of 3 arguments:
In [1]: def add(a, b, c):
...: return a+b+c
Normally to call it, you just specify the three arguments:
In [2]: add(1, 2, 3)
Out[2]: 6
Suppose the arguments were already in a list, what would you do? You
can't just pass the list, that is a single argument and you need three:
In [3]: data=[1, 2, 3]
In [4]: add(data)
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
<type 'exceptions.TypeError'>: add() takes exactly 3 arguments (1 given)
You could unpack the data yourself:
In [5]: a, b, c = data
In [6]: add(a, b, c)
Out[6]: 6
Or you can use the * notation, which basically means, "treat each
element of this list as a separate argument", or "use this list as the
argument list directly":
In [7]: add(*data)
Out[7]: 6
If the length of the argument list (data, in the example above) can
change, manually unpacking the list won't work and the * syntax is the
only alternative.
Kent
> 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)
More information about the Tutor
mailing list