mng*_*mng 4 python string list python-2.7
我想替换由字符串和子列表组成的列表中出现的所有字符串,如下所示:
myarray = ['Hello', 'how', 'how', ['are', 'what', 'how'], 'you', 'how']
Run Code Online (Sandbox Code Playgroud)
将更改为:
myarray = ['Hello', 'X', 'X', ['are', 'what', 'X'], 'you', 'X']
Run Code Online (Sandbox Code Playgroud)
到目前为止,我只能替换字符串中的“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
Run Code Online (Sandbox Code Playgroud)
这是它的输出:
['Hello', 'X', 'X', ['are', 'what', 'how'], 'you', 'X']
Run Code Online (Sandbox Code Playgroud)
我有什么想法可以解决这个问题吗?
我会为此编写一个递归函数。
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
Run Code Online (Sandbox Code Playgroud)
演示:
>> nestrepl(myarray, 'how', 'X')
>> myarray
['Hello', 'X', 'X', ['are', 'what', 'X'], 'you', 'X']
Run Code Online (Sandbox Code Playgroud)