Array construction from object members

Paul McGuire ptmcg at austin.rr._bogus_.com
Sat Dec 31 14:00:06 EST 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
> array,
<-snip->
>
Here's some sample code to show you how list comprehensions and generator
expressions do what you want.

-- Paul


class A(object):
    def __init__(self,val):
        self.a = val

    # define _repr_ to make it easy to print list of A's
    def __repr__(self):
        return "A(%s)" % str(self.a)

Alist = [ A(i*1.5) for i in range(5) ]

print Alist

# create new list of .a attributes, print, and sum
Alist_avals = [ x.a for x in Alist ]
print Alist_avals
print sum(Alist_avals)

# 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 mailing list