"filtered view" upon lists?
Raymond Hettinger
python at rcn.com
Tue Sep 12 21:02:28 EDT 2006
[Wildemar Wildenburger]
> I don't know how else to call what I'm currently implementing: An object
> that behaves like a list but doesn't store it's own items but rather
> pulls them from a larger list (if they match a certain criterion).
> Changes to the filter are instantly reflected in the underlying list.
> Clear enough?
Here's some code to try out:
import UserList
class ListView(UserList.UserList):
@property
def data(self):
return filter(self._filter_function, self._actual_list)
def __init__(self, actual_list, filter_function=None):
self._actual_list = actual_list
self._filter_function = filter_function
### Example calls
a = range(10)
b = ListView(a, lambda x: x%2==0)
print list(b), len(b), b[2], b[:3]
a[:] = range(10,20)
print list(b), len(b), b[2], b[:3]
Raymond Hettinger
More information about the Python-list
mailing list