gpt4 book ai didi

python - 创建嵌套/递归列表

转载 作者:行者123 更新时间:2023-11-28 20:57:31 24 4
gpt4 key购买 nike

如何递归创建列表?

我有这个列表:

l = ['a', 'b', 'new', 'c', 'd', 'new', 'z', 'x', 'c', 'fin', 'f', 'fin', 
'g', 'l', 'new', 'z', 'x', 'c', 'fin', 'j']

预期的输出是:

r = ['a', 'b', ['c', 'd', ['z', 'x', 'c'] 'f'], 'g', 'l', ['z', 'x', 'c'] 'j']

到目前为止我尝试了什么:

def asd(l, index=0):
r = []
for i in l[index:]:
index += 1
if i == 'new':
i, index = asd(l, index)
r.append(i)
if i == 'fin':
return r
return r, index

r, index = asd(l)

我不明白如何让它发挥作用。谁能帮帮我?

最佳答案

这是一种非递归解决方案,可以创建您的列表,一次解析,无需任何昂贵的 index() 操作:

l = ['a', 'b', 'new', 'c', 'd', 'new', 'f', 'fin', 'g', 'fin', 'j']

rv = []

curr = [rv] # things are always added to the last element if not 'fin' or 'new'

for elem in l:
if elem == "new":
# create a new list, put it at end of curr
curr.append([])
# add that list to the one before
curr[-2].append(curr[-1])
elif elem == "fin":
# done, remove from curr
curr.pop()
else:
curr[-1].append(elem)

print(rv)

输出:

['a', 'b', ['c', 'd', ['f'], 'g'], 'j']

l = ['a', 'b', 'new', '1', '2', '3', 'fin', 'c', 'new', 'x', 'y', 'z', 'fin',]  

导致

['a', 'b', ['1', '2', '3'], 'c', ['x', 'y', 'z']]

你需要针对不平衡/不正确的new/fin


在 Matthieu 的评论后进行了编辑以使其更加简洁。

关于python - 创建嵌套/递归列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52927495/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com