python - Is there an iter which accepts a complex sentinel? -
i use iter
2 arguments , wondering if there equivalent accept more complex sentinel?
as example, in code below
# returns digits 1 10 upon subsequently calling .create(), # returns 'end' each time afterwards class myclass: def __init__(self): self.counter = 0 def create(self): self.counter += 1 if self.counter > 10: return 'end' else: return self.counter c = myclass() in iter(c.create, 'end'): print(i)
the iteration ends upon getting 'end'
. have end after getting, say, total of 2 'end'
(not 1 after other - code above generate 'end'
after first ten calls 1 can imagine case interlaced other values).
in essence, looking way use more complex sentinel. there such concept?
i know can resort obvious-but-ugly code mentioned in previous question, hovewer @happyleapsecond answer elegant keep spirit (i went though itertools
none of available methods seem job)
you use itertools.takewhile
stateful predicate
. example:
>>> itertools import takewhile >>> def create_predicate(func, max_count): """return false when func evaluates true max_count time.""" def predicate(elem): if func(elem): predicate.count += 1 if predicate.count == max_count: return false return true predicate.count = 0 return predicate >>> list(takewhile(create_predicate(lambda elem: elem % 3 == 0, 3), range(1, 20))) [1, 2, 3, 4, 5, 6, 7, 8]
in example above, create_predicate(lambda elem: elem % 3 == 0, 3)
creates complex predicate function stop iteration on third multiple of three. in case,
i have end after getting, say, total of 2
'end'
you use create_predicate(lambda elem: elem == 'end', 2)
.
Comments
Post a Comment