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: Gerard Flanagan <grflanagan@yahoo.co.uk>
Date: Sat Dec 31 2005 - 18:16:03 CET

MKoool wrote:

> 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, for example, if i have a class like the following:
>
> class myClass:
> a = 0.0
>
> And lets say I populate the "a" element in an array of objects of
> myClass. If I want to retrieve all items in this and perhaps give it
> to a mean function, I would need to make a loop now:
>
> mySimpleArray = []
> for i in range(0,len(myArray)):
> mySimpleArray.append(myArray[i].a)
>
> There must be some more efficient way to do this, can someone point me
> to the right direction so that I can review some documentation and get
> things a little more efficient?
>
> thanks!

not sure if this is what you want to do, but does this help:

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

mylist = [ myclass('one'), myclass('two'), myclass('three'),
myclass('four') ]

alist = [ A.a for A in mylist ] #this is called a 'list comprehension'

print alist

output: ['one', 'two', 'three', 'four']

Gerard
Received on Tue Jan 3 03:29:14 2006