【问题标题】:Recursive call in python seems not to descendpython中的递归调用似乎没有下降
【发布时间】:2013-06-04 07:42:48
【问题描述】:

我有一个小函数来展平列表和元组。递归调用确实被调用了,但是..什么也没有发生。“什么都没有”我的意思是:不打印stderr消息,也没有产生任何结果。这种行为没有意义,所以指针表示赞赏。谢谢!

def flatten(*arr):
  sys.stderr.write("STDERR: arr is %s\n" %list(arr))
  for a in arr:
    if type(a) is list or type(a) is tuple:
      flatten(a)
    else:
      yield a

print list(flatten(['hi there','how are you'],'well there','what?',[1, 23423,33]))

【问题讨论】:

  • obj 是全局的吗?我没有看到它在任何地方定义。

标签: python recursion generator yield


【解决方案1】:

你的函数有几个问题。

首先,使用isinstance()来简化对序列的测试:

for a in arr:
    if isinstance(a, (list, tuple)):

您需要遍历递归 flatten() 调用以将元素传递给调用者,并将列表作为单独的参数传递(使用 * 语法,以反映函数签名):

for sub in flatten(*a):
    yield sub

通过这些更改,生成器可以工作:

>>> def flatten(*arr):
...     for a in arr:
...         if isinstance(a, (list, tuple)):
...             for sub in flatten(*a):
...                 yield sub
...         else:
...              yield a
... 
>>> print list(flatten(['hi there','how are you'],'well there','what?',[1, 23423,33]))
['hi there', 'how are you', 'well there', 'what?', 1, 23423, 33]

【讨论】:

  • 如果你使用 python 3.3,你可以使用 yield from 而不是循环遍历你的递归调用的值。
  • @oao:是的,但是 OP 使用的是 Python 2.x(使用 print 语句,而不是 print() 函数),所以我坚持这样做。
猜你喜欢
  • 2016-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-16
  • 2020-10-12
  • 2018-03-27
  • 1970-01-01
相关资源
最近更新 更多