Python's Generator expressions and Tuple pack/unpack is more powerful than I thought.
for k, v in d.iteritems():
if v > 123:
yield k, v
is equivalent to:
return (item for item in d.iteritems() if item[1] > 123)
Some simple generators can be coded using Generator expressions, and Tuple pack/unpack is an easy way to return multiple values.
% python
Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {'apple': 256, 'hoge': 123, 'orange': 555}
>>>
>>> def fn_yield():
... for k, v in d.iteritems():
... if v > 123:
... yield k, v
...
>>> def fn_generator():
... return (item for item in d.iteritems() if item[1] > 123)
...
>>> for k, v in fn_yield():
... print k, v
...
orange 555
apple 256
>>> for k, v in fn_generator():
... print k, v
...
orange 555
apple 256

0 comments:
Post a Comment