List transormation

Steven D. Majewski sdm7g at virginia.edu
Tue Sep 19 12:54:45 EDT 2000


On 19 Sep 2000, Andy Smith wrote:

> "Dale Strickland-Clark" <dale at out-think.NOSPAMco.uk> writes:
> 
> > Before I waste too much time on this, reinventing the wheel, is there a
> > quick way to reorder the items in a list under the control of another list?
> > 
> > e.g..
> > 
> > x = ['kipper', 'my', 'a', 'nose', 'is']
> > y = [1, 3, 4, 2, 0]
> > 
> > y transforms the order of x to produce:
> > 
> > ['my', 'nose', 'is', 'a', 'kipper']
> 
> >>> map (lambda n: x[n], y)
> ['my', 'nose', 'is', 'a', 'kipper']
> 
> This could be wrapped into a function taking arguments equivalent to x
> and y if you wanted to use it a lot.
> 

It would be nice if you could do:
  map( x.__getitem__, y )

but you can't. ( Why not ? Maybe this should be a PEP. )

You can do:

 >>> map( operator.__getitem__, [x]*len(y), y )
 ['my', 'nose', 'is', 'a', 'kipper']


which avoids having to add the "x=x" to the lambda when it's 
stuffed into a function. 


---|  Steven D. Majewski   (804-982-0831)  <sdm7g at Virginia.EDU>  |---
---|  Department of Molecular Physiology and Biological Physics  |---
---|  University of Virginia             Health Sciences Center  |---
---|  P.O. Box 10011            Charlottesville, VA  22906-0011  |---
		"All operating systems want to be unix, 
		 All programming languages want to be lisp." 




More information about the Python-list mailing list