enhanced map function

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Mar 11 20:19:49 EST 2011


On Fri, 11 Mar 2011 13:00:23 -0800, Patrick wrote:

> Hi,
> 
> The build-in map functions looks quite nice but it requests the
> iterables to be of the same length or otherwises will file with None
> (most of time fails the function). Just wondering if there are already
> enhancement work done with it?


That has been fixed in Python 3.1:

>>> from operator import add
>>> list(map(add, [1,2,3], [1,2,3,4,5]))
[2, 4, 6]

Starting from Python 2.3, the itertools module has had a function imap 
with the same behaviour:

>>> from operator import add
>>> list(itertools.imap(add, [1,2,3], [1,2,3,4,5]))
[2, 4, 6]


 
> I did some simple code but it will handle list without nesting only. 

Surely that is a good thing. If you have a mix of nested and non-nested 
data, that tells me your data is badly organized and needs to be fixed.


> I am looking for examples that could hand input of "a = [2,3], b=4" 

Using a small helper function:

import itertools

def make_iterable(obj):
    try:
        iter(obj)
    except TypeError:
        obj = itertools.cycle([obj])
    return obj

def enhanced_map(func, *args):
    args = map(make_iterable, args)
    return list(itertools.imap(func, *args))


WARNING: this is dangerous. If none of the arguments are iterable, e.g. 
you call enhanced_map(operator.add, 2, 3), this will happily loop forever 
building a larger and larger list, until you run out of memory or kill 
the Python process.


> and "a=[1,[2,3],4], b=[5,[6,7,8],9,10]". That means if the nesting
> structure is the same, enhanced map function will automatically extend
> the shorter list using the last element.

It isn't clear what you want here. Are you expecting this enhanced map to 
recursively drop down into each layer of sub-sequences? That is:

enhanced_map([1, [2,3, [4,5], 6], 7], [8, [7,6, [5,4], 3], 2])

should be the same as 

map([1, 2, 3, 4, 5, 6, 7], [8, 7, 6, 5, 4, 3, 2])

or something different?


What do you expect to happen if the sub-sequences don't match up exactly? 
E.g. a = [1, 2, [3, 4]]; b = [1, [2, 3], 4]

What do you expect to happen if the shorter list is empty?
E.g. a = [1, 2, [3, 4], 5]; b = [1, 2, [], 3]

This will get really messy fast. My advice is to forget about this as a 
bad idea, and instead concentrate on making sure your data isn't so badly 
arranged in the first place.



-- 
Steven



More information about the Python-list mailing list