array manipulation without for loops

Alex Martelli aleax at mac.com
Sun Jun 25 13:30:39 EDT 2006


Tim Chase <python.list at tim.thechases.com> wrote:
   ...
>  >>> all = [(x==255 or y==255) and (255, 255) or (x,y) for (x,y) 
> in itertools.izip(a1,a2)]
>  >>> b1 = [x[0] for x in all]
>  >>> b2 = [x[1] for x in all]
>  >>> a1, a2 = b1, b2 # if you want them to replace the originals
> 
> Seems to do what I understand that you're describing using "no" 
> loops (other than those implied by list comprehension).

Yep, but the performance cost of the for-loops in the comprehension is
essentially the same as for such loops written "normally".

> There may be some nice pythonic way to "unzip" a list of tuples 
> created by zip() but I couldn't scare up such a method, and 

Perhaps what you have in mind is:

>>> a=zip('feep','grol')
>>> a
[('f', 'g'), ('e', 'r'), ('e', 'o'), ('p', 'l')]
>>> zip(*a)
[('f', 'e', 'e', 'p'), ('g', 'r', 'o', 'l')]


But this wouldn't help the OP all that much with his performance
problems with large 2-D arrays (though it required some guessing to
gauge that it _was_ Numeric arrays that he was dealing with;-),


Alex



More information about the Python-list mailing list