如何在平面列表之外制作嵌套列表?

问题描述 投票:1回答:2

需要列出此示例列表

list = ["Hello","world","!!!"]

放入这样的嵌套列表中

new_list = ["Hello",["world",["!!!",None]]]

对于给定的任何平面清单。我可以用某种方式从嵌套列表中做出一个平面列表,但是经过数小时的尝试,我似乎找不到自己或谷歌搜索的解决方案。我已经在这里搜索过,但针对此特定问题一无所获。

谢谢您,如果这是一个愚蠢的问题。

python python-3.x list nested
2个回答
3
投票

您可以使用递归:

l = ["Hello","world","!!!"]
def to_list(d):
  return None if not d else [d[0], to_list(d[1:])]

print(to_list(l))

输出:

['Hello', ['world', ['!!!', None]]]

2
投票

这里是一个迭代解决方案:

def to_nested(seq):
    result = [seq[-1], None]
    for item in reversed(seq[:-1]):
        result = [item, result]
    return result


l = ["Hello","world","!!!"]
print(to_nested(l))
# ['Hello', ['world', ['!!!', None]]]

基本上是从列表的末尾开始构造目标嵌套列表,并继续用由先前元素及其早期自身组成的列表替换自身。


编辑

按时间顺序,这样更有效:

def to_nested_r(seq):
  return None if not seq else [seq[0], to_nested_r(seq[1:])]


%timeit to_nested(l * 100)
# 10000 loops, best of 3: 19.2 µs per loop
%timeit to_nested_r(l * 100)
# 10000 loops, best of 3: 167 µs per loop

并且不会达到最大递归限制:

to_nested_r(l * 1000)

[RecursionError:超过最大递归深度

while:

to_nested(l * 1000)

运行正常。

© www.soinside.com 2019 - 2024. All rights reserved.