Re: Array construction from object members
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: Array construction from object members

From: Paul McGuire <ptmcg@austin.rr._bogus_.com>
Date: Sat Dec 31 2005 - 20:00:06 CET

"MKoool" <mohankhurana@gmail.com> wrote in message
news:1136045997.504508.111410@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 )
Received on Tue Jan 3 03:29:22 2006