我想替换由字符串和子列表组成的列表中所有出现的字符串,所以像这样:
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 type(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']
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句