Using functional tools
Andrae Muys
amuys at shortech.com.au
Tue May 7 20:06:26 EDT 2002
Patrick W <quitelikely at yahoo.com.au> wrote in message news:<82sn58avea.fsf at acropolis.localdomain>...
> Patrick W <quitelikely at yahoo.com.au> writes:
>
> [...]
>
> Or, if the OP's religion forbids 'fors' or 'whiles' under any
> circumstances:
>
> def do_every_nth(seq, func, n):
> def transform(item, index):
> if index % n == n - 1: return func(item)
> else: return item
> return map(transform, seq, range(len(seq)))
Alternatively you can use the "obsolete" apply() and simplify the code
substantially.
def identity(x):
return x
def trans(x):
return x*10
>>> l = range(5)
>>> f = [identity, trans] # trans() every second item in list
>>>
>>> list(xmap(apply, xextend(f), zip(l)))
[0, 10, 2, 30, 4]
The zip() is required to convert the list of int's into a list of
tuple's for use by apply. Note you can use multiple argument
functions by simply adding extra sequence arguments to zip().
xextend => seq * infinity
xmap => lazy map, that terminates upon exhaustion of any of it's
arguments.
I implement these as follows:
def xmap(func, *args):
iterlist = [iter(arg) for arg in args]
while 1:
yield func(*[itr.next() for itr in iterlist])
def xextend(seq):
while 1:
for i in seq:
yield i
Andrae Muys
More information about the Python-list
mailing list