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 ?
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) .
2.1. Multiple Filters. The Stream API allows chaining multiple filters.
The findAny() method returns any element from a Stream, while the findFirst() method returns the first element in a Stream.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With