[Tutor] better map/lambda solution needed

Remco Gerlich scarblac@pino.selwerd.nl
Fri, 26 Apr 2002 08:13:09 +0200


On  0, lonetwin <lonetwin@yahoo.com> wrote:
> Hi everybody,
>      Firstly I'd like to say it's good to be back here, I was working on
>  non-python stuff lately (for about 3 months) and so missed all the fun
>  happening here :).
>  	Anyways, here's a quick question, is there a better way to express
> the following code (Note: I'm working on Python1.5). Actually, I know
> there should be....but somehow, I'm not seeing the obvious.
> Here goes :
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> >>> popList = ['steve', 'foo']
> >>> hostname = '@mail.foo'
> >>> for nick, user in map(None, map(lambda x: x+hostname, popList), popList):
> ...     print nick, user
> ...
> steve@mail.foo steve
> foo@mail.foo foo
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> 
> I have a problem with all that map(None, map(lambda ...) ...) stuff.
> Shows that I haven't been using python much, right ?? ;)

Or maybe it shows you're being over enthusiastic :)

Firstly, it won't work once you put this inside a function, it will only
work while 'hostname' is global - otherwise it can't be seen from inside the
lambda in 1.5. You have to pass it into the lambda as a default argument;
lambda x,hostname=hostname: x+hostname.

However, what is wrong with:

popList = ['steve', 'foo']
hostname = '@mail.foo'
for user in popList:
   print user+hostname, user
   
Isn't that easier? :)

-- 
Remco Gerlich