我想替换由字符串和子列表组成的列表中所有出现的字符串,所以像这样:
myarray = ['Hello', 'how', 'how', ['are', 'what', 'how'], 'you', 'how']
将更改为:
myarray = ['Hello', 'X', 'X', ['are', 'what', 'X'], 'you', 'X']
到目前为止,我只能替换字符串形式的“how”实例,而不是子列表中的实例。这是我目前的代码:
myarray = ['Hello', 'how', 'how', ['are', 'what', 'how'], 'you', 'how']
for n, i in enumerate(myarray):
for sublist in myarray:
if i == 'how':
myarray[n]="X"
print myarray
这是它的输出:
['Hello', 'X', 'X', ['are', 'what', 'how'], 'you', 'X']
有什么办法可以解决这个问题吗?
请您参考如下方法:
我会为此编写一个递归函数。
def nestrepl(lst, what, repl):
for index, item in enumerate(lst):
if isinstance(item, list):
nestrepl(item, what, repl)
else:
if item == what:
lst[index] = repl
演示:
>> nestrepl(myarray, 'how', 'X')
>> myarray
['Hello', 'X', 'X', ['are', 'what', 'X'], 'you', 'X']
