【问题标题】:Select level above in iteratively created nested list with Python在使用 Python 迭代创建的嵌套列表中选择上面的级别
【发布时间】:2017-02-16 19:32:30
【问题描述】:

我在列表中搜索了很多问题,但找不到我要找的东西。

我有一个字符串,其中包含一些值的大括号和一些包含值的其他嵌套大括号对。我不知道结构嵌套的最深层次,但它可能看起来像这样:

{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

我不知道如何上一级列表并关闭当前子列表

【问题讨论】:

  • 你可能想要一个递归解析函数。

标签: python list python-3.x nested


【解决方案1】:
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']

【讨论】:

  • 那么如何访问使用它创建的特定嵌套列表?
  • 说我是否想访问底层第二个子列表中的第二个项目?(在这种情况下是 1 - 以及右边的第三个数字)
  • 列表并不是很好。听起来你可能想要一个更像树的结构
  • 我在 python 中看到很多构建树的包,但是有树数据类型吗?因为我不想使用其他人的包,而只使用我自己的父/子索引系统的列表
【解决方案2】:

这是使用正则表达式和ast.literal_eval 创建一组元组的一种方法:

In [78]: s = "{121{12}12{211}2}"

In [79]: new = re.sub(r'(})(?!$)|(?<!^)({)',lambda x : {'{': ',(', '}': ',),'}[x.group(0)], s)

In [80]: ast.literal_eval(new)
Out[80]: {121, (211,), 2, 12, (12,)}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多