我在列表中搜索了很多问题,但找不到我要找的内容。
我有一个带有大括号的字符串,其中包含一些值和其他一些包含值的嵌套大括号对。我不知道结构嵌套的最深层次,但它可能看起来像这样:
{121{12}12{211}2}
我想迭代该字符串并将其传输到嵌套列表,其方式类似于以下伪代码:
for i in thestring
if there is a leftbrace { start a new list inside the current list
elseif there is a rightbrace } close the current list and select the list on the level above
else add i to currently selected list
我不知道如何上升列表级别并关闭当前子列表
最佳答案
def listify(s):
i = iter(s)
l = []
for c in i:
if c == '{':
l.append(listify(i))
elif c == '}':
return l
else:
l.append(c)
return l[0]
技巧是使用递归函数,以便堆栈负责跟踪您所在的列表。我们使用 iter
这样我们就可以将字符串传递给递归调用,而不需要字母我们已经处理过了。
>>>listify(s)
['1', '2', '1', ['1', '2'], '1', '2', ['2', '1', '1'], '2']
关于python - 使用 Python 在迭代创建的嵌套列表中选择上面的级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42283036/