我已经花了一些时间在这上面,但我还在学习,并且没有设法做到这一点。好吧,我做了,但我不想改变输入变量。
def changeit(element, value1, value2):
if type(element) == list:
for index, element2 in enumerate(element):
if element2 == value1:
element[index] = value2
if type(element2) == list:
changeit(element2, value1, value2)
if value1 not in element:
return element
def changelist(inputlist, value1, value2):
for index, element in enumerate(inputlist):
if type(element) == list:
changeit(element, value1, value2)
if element == value1:
inputlist[index] = value2
return inputlist
因此该函数应该替换value2的所有value1。所需的输出是:
>>> k = [[[7]], 8]
>>> print(changelist(k, 7, 'a'))
[[['a']], 8]
>>> k
[[[7]], 8]
但到目前为止我得到了:
>>> k = [[[7]], 8]
>>> print(changelist((k,7,"x"))
[[['x']], 8]
>>> k
[[['x']], 8]
而我却找不到如何不改变输入列表的方法。谢谢!
答案 0 :(得分:0)
def replace(l, old, new):
return [new if x == old else replace(x, old, new) if isinstance(x, list) else x for x in l]
这是使用列表推导的递归解决方案。这相当于
def replace(l, old, new):
ret = []
for x in l:
if x == old:
ret.append(new)
elif isinstance(x, list):
ret.append(replace(l, old, new))
else:
ret.append(x)
return ret