Array construction from object members
ptmcg at austin.rr._bogus_.com
Sat Dec 31 20:00:06 CET 2005
"MKoool" <mohankhurana at gmail.com> wrote in message
news:1136045997.504508.111410 at g14g2000cwa.googlegroups.com...
> Hi everyone,
> I am doing several operations on lists and I am wondering if python has
> anything built in to get every member of several objects that are in an
Here's some sample code to show you how list comprehensions and generator
expressions do what you want.
self.a = val
# define _repr_ to make it easy to print list of A's
return "A(%s)" % str(self.a)
Alist = [ A(i*1.5) for i in range(5) ]
# create new list of .a attributes, print, and sum
Alist_avals = [ x.a for x in Alist ]
# if original list is much longer...
Alist = [ A(i*1.5) for i in range(500000) ]
# ... creating list comprehension will take a while...
print sum( [ x.a for x in Alist ] )
# ... instead use generator expression - avoids creation of new list
print sum( x.a for x in Alist )
More information about the Python-list