FW: fast sub list operations

Paul Winkler slinkp23 at yahoo.com
Tue Oct 16 20:29:34 CEST 2001


On Tue, 16 Oct 2001 16:43:54 +0100, Dale Strickland-Clark
<dale at riverhall.NOTHANKS.co.uk> wrote:

>"Alves, Carlos Alberto - Coelce" <calves at coelce.com.br> wrote:
>>I constantly miss some nice way to subset lists. As an example suppose I
>>have a list of x y coordinates eg
>>
>>        [x0,y0,x1,y1,.....]
>>
>>and wish to perform the operation x->x+v, y->y+w for the co-ordinates in
>>the list I don't seem to be able to do this fast using map.
(snip)
>A simple class should help manipulate these lists:
>
>class pairs:
(snip)
>l = pairs(range(20))
>
>print 'Pairs', [[x, y] for x,y in l]
>print 'Odds', [y for x,y in l]
>print 'Evens', [x for x,y in l]
>print 'Doubled evens', [x*2 for x,y in l]

Depending on what Carlos needs to do with these lists, I wouldn't
bother with a class - I'd just make a list of [x,y] lists.

This could be constructed from the list Carlos already has like so:

def pairs(alist):
    return [[alist[i], alist[i+1]] for i in range(0,len(alist),2)]

Then the rest of your examples work exactly as you've written them.
Easy to use with map(), too:

>>> spam = pairs(range(10))
>>> spam
[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]
>>> map(lambda coord: [coord[0] +10, coord[1] +20], spam)
[[10, 21], [12, 23], [14, 25], [16, 27], [18, 29]]


--PW





More information about the Python-list mailing list