Partition list with predicate

Brian breily at gmail.com
Wed Apr 23 21:14:18 EDT 2008


On Wed, Apr 23, 2008 at 9:08 PM, Jared Grubb <jared.grubb at gmail.com> wrote:

> I guess I forgot one requirement: the removed elements need to be
> remembered.
>
> Basically, I have a list of objects in a buffer, one class operates on
> some of the objects, but other classes use others. So, a class must extract
> the ones it can handle, and leave the rest in the buffer for the other
> classes to handle.
>
> I haven't found a function that will both remove objects from a list, but
> save the ones that do get removed.
>
> Jared
>
> On 23 Apr 2008, at 10:15, Tim Golden wrote:
>
> Jared Grubb wrote:
>
> I want a function that removes values from a list if a predicate evaluates
> to True. The best I could come up with is:
>
>
> Have a look at the itertools module, and the ifilter function
> in particular.
>
> TJG
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I would do it like this:

# This takes out the values
extracted = [ obj for obj in lst if pred(obj) ]
# This filters out any item that was extracted
lst = [ obj for obj in list if obj not in extracted ]

Brian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080423/78f2ae4a/attachment.html>


More information about the Python-list mailing list