i'm wondering whether there's more pythonic way interval list knowing beginning , ending values while traversing list once.
example of want in not pythonic manner (stores names between 'ann' , 'john' inclusive):
all_names = [] start_adding = false name in names: if name == 'ann': start_adding = true if start_adding: all_names.append(name) if name == 'john': break
that solution traverses list once. , uses 1 expression , functions standard library! :)
import itertools l = ['bill', 'patrick', 'aaron', 'ann', 'jane', 'rachel', 'beatrix', 'john', 'basil', 'alice', ] l = iter(l) print( list( it.chain( it.dropwhile(lambda _: true, iter(lambda: next(l), 'ann')), iter(lambda: next(l), 'john') ) ) )
output:
['jane', 'rachel', 'beatrix']
also - demo: http://ideone.com/eolg6o
Comments
Post a Comment