"filtered view" upon lists?
ptmcg at austin.rr._bogus_.com
Tue Sep 12 16:12:13 CEST 2006
"Jorge Godoy" <jgodoy at gmail.com> wrote in message
news:878xkpb5wa.fsf at gmail.com...
> Wildemar Wildenburger <wildemar at freakmail.de> writes:
>> I don't know how else to call what I'm currently implementing: An object
>> behaves like a list but doesn't store it's own items but rather pulls
>> 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
>> then finding it in the libs some weeks later.).
> I don't believe it is generic. Nobody knows your data specs or filtering
>> 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>
Functionally-speaking, there is the filter built-in that does this same
>>> data = range(10)
>>> odds = filter(lambda x : x % 2, data)
>>> evens = filter(lambda x : x % 2 != 1, data)
[1, 3, 5, 7, 9]
[0, 2, 4, 6, 8]
More information about the Python-list