【问题标题】:Replacing an element in recursive nested list python替换递归嵌套列表python中的元素
【发布时间】:2015-03-15 05:33:28
【问题描述】:

我想像这样替换递归嵌套列表中的元素:

["not", ["or",["not",["or",["not",["or",["P",["not", "Q"]]],"R"]],["and","P,"R"]]]

我想将“不”向内移动。所以基本上,“or”被“and”取代,“and”被“or”取代,“not”不应该出现在列表中,除了变量,比如[“not”,“R”]是可以的但是 ["not",["not","P"]] 应该只是 P。请帮帮我。我已经准备好了大部分代码,但是我无法替换原始数组,因为我正在使用递归移动到最里面的元素,并且当我向外移动时,我必须能够用我所做的更改替换最里面的元素我做不到。请帮帮我。

【问题讨论】:

  • 请向我们展示您的代码。
  • 您的列表格式似乎没有意义。 andor 元素应该正好有两个兄弟元素,not 元素应该正好有一个。您的列表中有一个 not 有两个兄弟姐妹,还有一个 or 没有。您还在某处缺少双引号(看起来像在最后一个 P 之后),但修复此问题并不能解决兄弟问题。

标签: python artificial-intelligence computer-science


【解决方案1】:

您可以使用函数和for 循环递归替换元素。

def clean(lst, string_to_replace):
    newlst = lst[:]

    for idx, elem in enumerate(lst):
        if isinstance(elem, list):
            lst[idx] = check(lst[idx], string_to_replace)
        elif isinstance(elem, str):
            if lst[idx] == replace:
                del newlst[idx]
        else:
            continue

    return newlst

还有你提供的清单:

>>> mylist = ["not", ["or",["not",["or",["not",["or","P",["not", "Q"]]]],"R"]],["and","P","R"]]
>>> clean(mylist, 'not')
[['or', [['or', [['or', 'P', ['Q']]]], 'R']], ['and', 'P', 'R']]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2014-03-06
    • 2012-07-26
    • 2021-01-12
    • 2018-04-18
    • 2013-06-26
    • 2014-08-13
    相关资源
    最近更新 更多