for , ordering

Bengt Richter bokr at oz.net
Thu Jun 6 15:17:31 EDT 2002


On Thu, 6 Jun 2002 17:51:53 GMT, Andrew Koenig <ark at research.att.com> wrote:

>gabor> for obj1 in objects1:
>gabor> objects2.append(obj2(obj1.x))
>
>
>gabor> 1. isn't there a more elegant way to do this?
>
>ark> Isn't this the same as saying
>
>ark>         objects2 = objects1[:]
>
>ark> ?  Am I missing something obvious?
>
Misplaced coffee mug? I know that one ;-)

>The answer is yes:  I *am* missing something obvious:  I didn't
>notice the obj2(obj1.x).  But why not
>
>             objects2 = map(lambda x: obj2(obj1.x), objects1)
Um,
              objects2 = map(lambda y: obj2(y.x), objects1)
?
E.g., (for others ;-)

 >>> class X:
 ...     def __init__(self,v): self.x=v
 ...     def __str__(self): return '<from X(%s)>' % self.x
 ...     __repr__ = __str__
 ...
 >>> objects1 = [X(i) for i in xrange(5)]
 >>> objects1
 [<from X(0)>, <from X(1)>, <from X(2)>, <from X(3)>, <from X(4)>]
 >>> def obj2(x): return '<obj2(%s)>' % x
 ...
 >>> objects2  = map(lambda y: obj2(y.x), objects1)
 >>> objects2
 ['<obj2(0)>', '<obj2(1)>', '<obj2(2)>', '<obj2(3)>', '<obj2(4)>']

>
>?
 >>> map(lambda x: obj2(obj1.x), objects1)
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 1, in <lambda>
 NameError: global name 'obj1' is not defined

I'd second Eric's suggestion though:

 >>> objects2_eric = [obj2(obj1.x) for obj1 in objects1]
 >>> objects2_eric
 ['<obj2(0)>', '<obj2(1)>', '<obj2(2)>', '<obj2(3)>', '<obj2(4)>']

Regards,
Bengt Richter



More information about the Python-list mailing list