Re: Array construction from object members



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

.



Relevant Pages

  • Array construction from object members
    ... 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: ...
    (comp.lang.python)
  • (patch for Bash) regex(3) splitting/matching
    ... I usually do this in Python. ... 'help array' will give you more info on other options for 'array' ... int dollarflag, zeropad, compareflag; ... SHELL_VAR *var; ...
    (comp.unix.shell)
  • Re: Why C Is Not My Favourite Programming Language
    ... And the number of modules in Python 2.4's Global Module Index is 362. ... The PDP architecture ideals ... fflushcan't be used to flush the contents of standard ... But it's not foolish that in ksh if you refer to an array name ...
    (comp.lang.c)
  • Re: Allowing zero-dimensional subscripts
    ... The items of a tuple are arbitrary Python objects. ... items are formed by comma-separated lists of expressions. ... the grammar rule used for list subscript is different from the ... an array with n-dimensions of length 3 would have ...
    (comp.lang.python)
  • Re: Brain going crazy with recursive functions
    ... I want eventually to port this to scheme, but I know python ... I'm in linear_search for the array, I also call linear_search for each ... return linear_search_iter(0, truth_func, array, acc) ...
    (comp.lang.python)