Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中取消列表的平台化_Python_Python 2.7_Recursion_Iteration - Fatal编程技术网

在python中取消列表的平台化

在python中取消列表的平台化,python,python-2.7,recursion,iteration,Python,Python 2.7,Recursion,Iteration,问题: 编写一个名为“unflatten”的函数,该函数将列表作为参数 并构造一个嵌套列表 参数列表的格式如下所示: 整数项表示嵌套列表非整数项的开始 将是嵌套列表的内容,例如 [2',a',3',b',c',d']被转换为['a',['b',c',d'] 第一个数字2表示上面的列表将包含2项。 'a'是上面列表的第一项。数字3表示一个数字 开始包含3个项目的新子列表 样本运行: >>> unflatten([2, 'x', 'y']) ['x', 'y'] >>&

问题:

编写一个名为“unflatten”的函数,该函数将列表作为参数 并构造一个嵌套列表

参数列表的格式如下所示:

整数项表示嵌套列表非整数项的开始 将是嵌套列表的内容,例如

[2',a',3',b',c',d']
被转换为
['a',['b',c',d']
第一个数字2表示上面的列表将包含2项。
'a'
是上面列表的第一项。数字3表示一个数字 开始包含3个项目的新子列表

样本运行:

>>> 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']]]]]]
正如您所看到的,列表的长度在我的基本递归中是不受控制的,所以它只是在末尾结束所有列表


我不知道如何递归或迭代跟踪长度。如果您能建议一种不导入任何模块的方法,我将非常高兴。

跟踪职位的一种方法是返回职位。在下面的代码中,我使用了一个helper函数,它返回部分构建的非平坦列表以及平坦列表中的当前索引

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" ])

您必须考虑到,如果
isinstance(LIST[0],int)
,那么接下来就有
LIST[0]
元素。您可以使用一个助手函数,
unflatten(l)
可以调用
unflatten_bis(l[1:],l[0])
并且
unflatten_bis
将完成所有工作。(只是一个建议)