Good use for itertools.dropwhile and itertools.takewhile

Nick Mellor thebalancepro at gmail.com
Wed Dec 5 02:17:56 CET 2012


Hi Terry,

For my money, and especially in your versions, despite several expert solutions using other features, itertools has it. It seems to me to need less nutting out than the other approaches. It's short, robust, has a minimum of symbols, uses simple expressions and is not overly clever. If we could just get used to using takewhile.

takewhile mines for gold at the start of a sequence, dropwhile drops the dross at the start of a sequence.

Thanks all for your interest and your help,

Best,

Nick

Terry's implementations:

> from itertools import takewhile
> 
> def allcaps(word): return word == word.upper()
> 
> 
> 
> def split_product_itertools(s):
> 
>      product = ' '.join(takewhile(allcaps, s.split()))
> 
>      return product, s[len(product)+1:]
> 
> 
> 
> print(split_product_itertools("CAPSICUM RED fresh from QLD"))
> 
>  >>>
> 
> ('CAPSICUM RED', 'fresh from QLD')
> 
> 
> 
> [if there could be surplus whitespace], the same idea applies to the split list.
> 
> 
> 
> def split_product_itertools(s):
> 
>      words = s.split()
> 
>      product = list(takewhile(allcaps, words))
> 
>      return ' '.join(product), ' '.join(words[len(product):])
> 



More information about the Python-list mailing list