生成器和收益声明 [英] Generators and yield statement

查看:89
本文介绍了生成器和收益声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想创建一个需要迭代的函数.该可迭代对象可以包含任何级别的其他可迭代对象.我想创建一个按顺序遍历这些函数.例如:

Suppose I want to create a function that takes an iterable. That iterable may contain other iterables to any level. I want to create a function that goes over these in order. So for example:

import collections
def it(l):
  for i in l:
    if isinstance(i, collections.Iterable):
      it(i) 
    else:
      print i


it([ [1, 2, 3], [[4, [5, 6]], 7], 8, [9, 10]])  

这将产生以下输出(按预期): 1个 2个 3 4 5 6 7 8 9 10

This produces the following output (as expected): 1 2 3 4 5 6 7 8 9 10

我想我不应该使用生成器来做到这一点.为什么下面的代码不能按我期望的那样工作(本质上是用yield代替print语句):

No supposed I want to do this with a generator. Why doesn't the following work as I would expect it to (essentially replacing the print statement with a yield) :

import collections
def it(l):
  for i in l:
    if isinstance(i, collections.Iterable):
      it(i) 
    else:
      yield i

谢谢!

推荐答案

因为递归,您返回了一个新的生成器-但是该生成器从不产生任何东西,因为您没有对其进行迭代.相反,请执行以下操作:

because when you recurse, you return a new generator -- But that generator never yields anything because you don't iterate over it. Instead, do something like:

def it(l):
  for i in l:
    if isinstance(i, collections.Iterable):
      for item in it(i):
        yield item
    else:
      yield i

或者,在python3.3中,您可以使用 yield from 关键字

Or, in python3.3, you can use the yield from keyword.

这篇关于生成器和收益声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆