Good use for itertools.dropwhile and itertools.takewhile

DJC djc at news.invalid
Tue Dec 4 13:28:44 EST 2012


On 04/12/12 17:18, Alexander Blinne wrote:
> Another neat solution with a little help from
>
> http://stackoverflow.com/questions/1701211/python-return-the-index-of-the-first-element-of-a-list-which-makes-a-passed-fun
>
>>>> def split_product(p):
> ....     w = p.split(" ")
> ....     j = (i for i,v in enumerate(w) if v.upper() != v).next()
> ....     return " ".join(w[:j]), " ".join(w[j:])
>
Python 2.7.3 (default, Sep 26 2012, 21:51:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> w1 = "CAPSICUM RED Fresh from Queensland"
 >>> w1.split()
['CAPSICUM', 'RED', 'Fresh', 'from', 'Queensland']
 >>> w = w1.split()

 >>> (i for i,v in enumerate(w) if v.upper() != v)
<generator object <genexpr> at 0x18b1910>
 >>> (i for i,v in enumerate(w) if v.upper() != v).next()
2

Python 3.2.3 (default, Oct 19 2012, 19:53:16)

 >>> (i for i,v in enumerate(w) if v.upper() != v).next()
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: 'generator' object has no attribute 'next'




More information about the Python-list mailing list