Re: Array construction from object members
- From: "Paul McGuire" <ptmcg@xxxxxxxxxxxxxxxxxxxxx>
- Date: Sat, 31 Dec 2005 19:00:06 GMT
"MKoool" <mohankhurana@xxxxxxxxx> wrote in message
news:1136045997.504508.111410@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
> 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 )
.
- References:
- Array construction from object members
- From: MKoool
- Array construction from object members
- Prev by Date: Re: bsddb3 locking questions
- Next by Date: Re: Vector math library
- Previous by thread: Re: Array construction from object members
- Index(es):
Relevant Pages
|