"filtered view" upon lists?
Jorge Godoy
jgodoy at gmail.com
Tue Sep 12 08:56:05 EDT 2006
Wildemar Wildenburger <wildemar at freakmail.de> writes:
> 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?
It looks like you're implementing a callable to me. This is a method that
returns results based on some input -- here your original list and filter.
Then you'll use this method wherever you need that filtered list.
> Ok, so I figured that this is generic enough to be found in some standard
> module already (I've had this often enough: Painfully implementing s/th and
> then finding it in the libs some weeks later.).
I don't believe it is generic. Nobody knows your data specs or filtering
needs.
> Any pointers?
Use of list comprehension might make it easier to code this:
def myCallable(my_list, filter):
filtered_list = [(item) for item in my_list if filter(item)]
return filtered_list
Example of full code:
>>> test_list = range(10)
>>> filter = lambda x: not x%2
>>> def myCallable(list, filter):
... filtered_list = [(item) for item in list if filter(item)]
... return filtered_list
...
>>> myCallable(test_list, filter)
[0, 2, 4, 6, 8]
>>> for item in myCallable(test_list, filter):
... print "See? I'm", item
...
See? I'm 0
See? I'm 2
See? I'm 4
See? I'm 6
See? I'm 8
>>>
--
Jorge Godoy <jgodoy at gmail.com>
More information about the Python-list
mailing list