Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filtered and non-filtered elements in a single pass

Filter function returns a sublist of elements which return true for a given function. Is it possible to get the list of elements which return false in a different list without going over the entire list again.

Example:

trueList,falseList = someFunc(trueOrFalseFunc,list)

PS : I know it can be done by initializing two empty lists and appending elements to each based on the return value of the function. The list under consideration can be potentially very huge and there might very few elements that might return true. As the append function is costly, is there a better way to do it ?

like image 301
Graddy Avatar asked Apr 09 '12 20:04

Graddy


People also ask

Can we use two filter in stream Java?

Combining two filter instances creates more objects and hence more delegating code but this can change if you use method references rather than lambda expressions, e.g. replace filter(x -> x. isCool()) by filter(ItemType::isCool) .

Can we have multiple filter in stream?

2.1. Multiple Filters. The Stream API allows chaining multiple filters.

What is the difference between findFirst and findAny Java 8?

The findAny() method returns any element from a Stream, while the findFirst() method returns the first element in a Stream.

How does stream and filter work in Java?

The filter() function of the Java stream allows you to narrow down the stream's items based on a criterion. If you only want items that are even on your list, you can use the filter method to do this. This method accepts a predicate as an input and returns a list of elements that are the results of that predicate.


1 Answers

Try this, using iterators:

from itertools import tee

def partition(lst, pred):
    l1, l2 = tee((pred(e), e) for e in lst)
    return (x for cond, x in l1 if cond), (x for cond, x in l2 if not cond)

Use it like this, and remember that the values returned are iterators:

lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
evens, odds = partition(lst, lambda x: x%2 == 0)

If you need lists for some reason, then do this:

list(evens)
> [0, 2, 4, 6, 8]
list(odds)
> [1, 3, 5, 7, 9]
like image 68
Óscar López Avatar answered Sep 21 '22 18:09

Óscar López