在python中取消列表 [英] Unflattening a list in python
问题描述
问题:
编写一个名为unflatten的函数,它将一个列表作为参数
并构造一个嵌套列表。
Write a function named "unflatten" which takes a list as an argument and constructs a nested list.
参数列表的格式如下:
整数项表示嵌套的开始list非整数项
将是嵌套列表的内容例如,
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']转换为['a',['b','c','d']]
第一个数字2表示上面的列表将包含2个项目。
'a'是此上排列表的第一项。数字3表示新的子列表的
开始,其中包含3个项目。
[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']]]
我做了一个简单的递归。这是我的代码:
I have done a simple recursion. Here is my code:
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']]]]]]
现在你可以看到,列表长度不受控制在我的基本递归中,所以它只是在结尾处结束所有列表。
Now as you can see, lengths of lists are not controlled in my basic recursion, so it simply ends all the lists at the end.
我不知道如何递归地或者可能迭代地跟踪长度。如果你建议这样做而不导入任何模块,我会很高兴。
I don't know how I can track the lengths recursively, or maybe iteratively. I'd be glad if you suggest a way doing this without importing any modules.
推荐答案
跟踪位置的一种方法归还它。在下面的代码中,我使用一个辅助函数,它返回部分构建的unflattened列表以及展平列表中的当前索引。
One way to keep track of the position is by returning it. In the code below I use a helper function that returns the partially-built unflattened list as well as the current index in the flattened list.
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中取消列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!