473,398 Members | 2,404 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

Array construction from object members

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!

Dec 31 '05 #1
3 1162
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

Dec 31 '05 #2
"MKoool" <mo**********@gmail.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.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 )
Dec 31 '05 #3
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.

Jan 1 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: ip4ram | last post by:
I used to work with C and have a set of libraries which allocate multi-dimensional arrays(2 and 3) with single malloc call. data_type **myarray =...
47
by: VK | last post by:
Or why I just did myArray = "Computers" but myArray.length is showing 0. What a hey? There is a new trend to treat arrays and hashes as they were some variations of the same thing. But they...
1
by: jimbo | last post by:
Here is my problem. I'm creating an Instrumentation class that will use previously created Performance Categories and Counters in order to time various processes (ie. query duration etc.). This...
104
by: Leszek | last post by:
Hi. Is it possible in javascript to operate on an array without knowing how mamy elements it has? What i want to do is sending an array to a script, and this script should add all values from...
4
by: gg9h0st | last post by:
i'm a newbie studying php. i was into array part on tutorial and it says i'll get an array having keys that from member variable's name by converting an object to array. i guessed "i can...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.