python - 在 python 中展开列表

标签 python python-2.7 recursion iteration

问题:

Write a function named "unflatten" which takes a list as an argument and constructs a nested list.

The format of the argument list is as follows:

An integer item indicates a start of a nested list Non-integer items will be the content of the nested list For instance,

[2, 'a', 3, 'b', 'c', 'd'] is converted to ['a', ['b', 'c', 'd']] The first number, 2, indicates that the upper list will contain 2 items. 'a' is the first item of this upper list. The number 3 indicates a start of a new sub-list which contains 3 items.

示例运行:

>>> unflatten([2, 'x', 'y'])
['x', 'y']
>>> unflatten([ 3, "a", "b", 3, "t", "y", "u" ])
['a', 'b', ['t', 'y', 'u']]
>>> unflatten([ 4, "a", "b", 3, "c", "d", 2, "x", "y", 2, "w" , 3, "t", "y", "u" ])
['a', 'b', ['c', 'd', ['x', 'y']], ['w', ['t', 'y', 'u']]]

我做了一个简单的递归。这是我的代码:

def unflatten(LIST):
    if not len(LIST):
       return []
    elif isinstance(LIST[0], int):
        return [unflatten(LIST[1:])]
    else:
        return [LIST[0]]  + unflatten(LIST[1:])


>>> unflatten([ 4, "a", "b", 3, "c", "d", 2, "x", "y", 2, "w" , 3, "t", "y", "u" ])
[['a', 'b', ['c', 'd', ['x', 'y', ['w', ['t', 'y', 'u']]]]]]

现在如您所见,列表的长度在我的基本递归中不受控制,因此它只是在末尾结束所有列表。

我不知道如何递归或迭代地跟踪长度。如果您建议一种无需导入任何模块即可执行此操作的方法,我会很高兴。

最佳答案

跟踪位置的一种方法是返回它。在下面的代码中,我使用一个辅助函数,该函数返回部分构建的未展平列表以及展平列表中的当前索引。

def unflatten(l):
  def helper(l, start):
    if isinstance(l[start], int):
      ret = []
      start += 1
      for _ in range(l[start - 1]):
        sub, start = helper(l, start)
        ret.append(sub)
      return ret, start
    else:
      return l[start], start + 1
  return helper(l, 0)[0]

print unflatten([2, 'x', 'y'])
print unflatten([ 3, "a", "b", 3, "t", "y", "u" ])
print unflatten([ 4, "a", "b", 3, "c", "d", 2, "x", "y", 2, "w" , 3, "t", "y", "u" ])

关于python - 在 python 中展开列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27620855/

相关文章:

python - 从python检测macos中的暗模式

python - 如何从Python中的字典列表中合并字典?

javascript - JavaScript 中的递归以在大量 JSON 中进行搜索

Python - 从外部文本文件创建字典

python - 调整文本背景透明度

python - pandas 加入 DataFrame 强制后缀?

python - 在图像上进行一定次数的绘制后,枕头在保存时给出 "unknown raw mode"

python - 如何使用scrapy抓取Google Play网站

使用递归反转堆栈的 C 程序

java - 如何避免在递归中重复检查?