gpt4 book ai didi

python - 如何将字符串格式的嵌套列表转换为列表(递归或迭代方式)

转载 作者:行者123 更新时间:2023-12-05 02:37:53 32 4
gpt4 key购买 nike

我有这个字符串 [1,[2,3],[4,5,6],[7,[8,90],10],[11,120,[13]]]" 作为输入。如何使用递归或迭代将此字符串转换为列表,但不在 Python 中导入?

这是我试过的。此解决方案仅适用于我输入的字符串 "[1,[2,3]]" 部分。

预期的输出是 [1,[2,3],[4,5,6],[7,[8,90],10],[11,120,[13]]]

l = "[1,[2,3],[4,5,6],[7,[8,90],10],[11,120,[13]]]"

def convert(l,out=[],i=0):
while i<len(l)-1:
if l[i] == "]":
return out,i
if l[i] =="[":
out_to_add,index = convert(l[i+1:],[])
out.append(out_to_add)
i+=index
elif l[i]!=",":
out.append(l[i])
i+=1
print(convert(l)[0][0])

编辑:注意。这是一项任务,不允许导入

最佳答案

更短的无导入解决方案:

l = "[1,[2,3],[4,5,6],[7,[8,90],10],[11,120,[13]]]"
def to_list(d):
while d and (n:=d.pop(0)) != ']':
if n == '[':
yield list(to_list(d))
elif n.isdigit():
yield int(n+(x:=lambda :'' if not d[0].isdigit() else d.pop(0)+x())())

print(next(to_list(list(l))))

输出:

[1, [2, 3], [4, 5, 6], [7, [8, 90], 10], [11, 120, [13]]]

关于python - 如何将字符串格式的嵌套列表转换为列表(递归或迭代方式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69862872/

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