The best, effective way to get a tuple of the result of a sequence of elements that fulfill and do not fulfill the condition

(This is a professional best practice / interest in the template, not a home request)

  • INPUT : any unordered sequence or generator elements , the myfilter (item) function returns True if the filter condition is satisfied p>

  • OUTPUT : (filter_true, filter_false) tuple of sequences is an original type that contains elements separated according to the filter in the original sequence order.

How would you express this without double filtering, or should I use double filtering? Maybe the answer to filtering and the loop / generator / list using nextcan be answered?

Do I have to accept the requirement to keep the type or just change the requirement, giving the tuple of the result of the tuple / generator, I can not easily return the generator to input the generator, or can I? (DIY requirements)

Here's the test of the best candidate at the moment, offering two threads instead of a tuple

import itertools as it
from sympy.ntheory import isprime as myfilter

mylist = xrange(1000001,1010000,2)
left,right = it.tee((myfilter(x), x) for x in mylist)
filter_true = (x for p,x in left if p)
filter_false = (x for p,x in right if not p)

print 'Hundred primes and non-primes odd  numbers'
print  '\n'.join( " Prime %i, not prime %i" %
                  (next(filter_true),next(filter_false))
                  for i in range(100))
+3
source share
4 answers

Here is a way to do this, which only calls myfilteronce for each element and will work if it mylistis a generator

import itertools as it
left,right = it.tee((myfilter(x), x) for x in mylist)
filter_true = (x for p,x in left if p)
filter_false = (x for p,x in right if not p)
+5

, - , cpu, myfilter , . :

(memoryvorous):

filter_true=[]
filter_false=[]
for item in  items:
    if myfilter(item):
        filter_true.append(item)
    else:
        filter_false.append(item)  

, : ( ( ()))

while items:
    item=items.pop()
    if myfilter(item):
        filter_true.append(item)
    else:
        filter_false.append(item)  

:

while True:
    try:
        item=next(items)
        if myfilter(item):
            filter_true.append(item)
        else:
            filter_false.append(item)  
    except StopIteration:
        break
+2

( ) tee iterable :

import itertools
left, right = itertools.tee( mylist )
filter_true = (x for x in left if myfilter(x))
filter_false = (x for x in right if myfilter(x))

, , myfilter . , left, right, . , : tee . deque , , , .

0

, :

filter_true = (x for x in mylist if myfilter(x))
filter_false = (x for x in mylist if not myfilter(x))
-1

Source: https://habr.com/ru/post/1763416/


All Articles