Array construction from object members

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Jan 1 01:30:29 EST 2006


On Sat, 31 Dec 2005 09:01:44 -0800, 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

Did you mean for a to be a class attribute? You possibly want something
like this:

class myClass:
    def __init__(self, value=0.0):
        self.a = value  # "a" for attribute

Then you can create new instances:

fred = myClass(2.7)
wilma = myClass()  # just use the default
betty = myClass(1.3)
barney = myClass(0.9)


> 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?

myArray = [fred, wilma, betty, barney]

mySimpleArray = []
for person in myArray:
    mySimpleArray.append(person.a)


Or try this:

mySimpleArray = [person.a for person in myArray]

Or this:

def mean_value(*people):
    """Takes a list of people and returns the mean of their attributes"""
    total = 0.0
    for person in people:
        total += person.a
    return total/len(people)

mean_value(fred, betty, barney, wilma)

That last version is not recommended, because it requires a separate
function for everything you want to calculate. For instance, if you add a
second attribute "height" to myClass, and want to work out the mean
height, you would need a second function to do it.



-- 
Steven.




More information about the Python-list mailing list