我想替换递归嵌套列表中的元素,如下所示:
["not", ["or",["not",["or",["not",["or",["P",["not", "Q"]]],"R"]],["and","P,"R"]]]
我想向内移动“不”。所以基本上,“或”被“和”取代,“和”被“或”取代,“不”不应该再出现在列表中,除了变量,如[“not”,“R”]是好的但是[“不”,[“不是”,“P”]]应该只是P.请帮助我。我已经准备好了大部分代码,但我无法替换原始数组,因为我使用递归移动到最里面的元素,因为我向外移动,我必须能够用我所做的更改来替换最内在的元素我无法做到。请帮帮我。
答案 0 :(得分:0)
您可以使用函数和for
循环来递归替换元素。
mylist = ["not", ["or",["not",["or",["not",["or","P",["not", "Q"]]]],"R"]],["and","P","R"]]
def check(lst, replace):
newlst = lst[:]
for index, item in enumerate(lst):
if type(item) is list:
lst[index] = check(lst[index], replace)
elif type(item) is str:
if lst[index] == replace:
del newlst[index]
return newlst
然后获取新列表:
>>> print(check(mylist, 'not'))
[['or', [['or', [['or', 'P', ['Q']]]], 'R']], ['and', 'P', 'R']]