get list of member variables from list of class

Peter Otten __peter__ at web.de
Fri Jan 28 04:33:30 EST 2005


Oliver Eichler wrote:

> 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.
 
>>> class A:
...     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
<__main__.List instance at 0x402ae2cc>
>>> 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





More information about the Python-list mailing list