get list of member variables from list of class

O

Oliver Eichler

Hi

what will be the fastest solution to following problem

class a:
def __init__(self):
self.varA = 0
self.varB = 0
s.o. ...


listA = [a]*10


varA = []
varB = []

for l in listA:
varA.append(l.varA)
varB.append(l.varB)
s.o. ...


I could think of:
[varA.append(l.varA) for l in listA]
[varB.append(l.varB) for l in listA]
s.o. ...

But is this faster? After all I have to iterate over listA several times.

Any better solutions?


Oliver
 
P

Peter Otten

Oliver said:
what will be the fastest solution to following problem

class a:
def __init__(self):
self.varA = 0
self.varB = 0
s.o. ...


listA = [a]*10


varA = []
varB = []

for l in listA:
varA.append(l.varA)
varB.append(l.varB)
s.o. ...


I could think of:
[varA.append(l.varA) for l in listA]
[varB.append(l.varB) for l in listA]
s.o. ...

But is this faster? After all I have to iterate over listA several times.

Any better solutions?

A different approach, a "virtual list" could even be faster if client code
must access only a fraction of the items in the virtual list. If you are
lucky, you never have to iterate over the complete list.
.... def __init__(self, a):
.... self.a = a
.... def __repr__(self):
.... return "A(%r)" % self.a
....
items = map(A, range(10))
items [A(0), A(1), A(2), A(3), A(4), A(5), A(6), A(7), A(8), A(9)]
class List:
.... def __init__(self, items, getter):
.... self.items = items
.... self.getter = getter
.... def __getitem__(self, index):
.... return self.getter(self.items[index])
.... def __iter__(self):
.... return imap(self.getter, self.items)
....
from operator import attrgetter
from itertools import imap
items_a = List(items, attrgetter("a"))
items_a
items_a[2] 2
list(items_a) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
items[2] = A(42)
items [A(0), A(1), A(42), A(3), A(4), A(5), A(6), A(7), A(8), A(9)]
items_a[2]
42

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top