How to replace a string from a list of lists using the string.replace node

Hi,

a solution (multi list level) with numpy, if input list is homogeny

import sys
import clr

clr.AddReference('Python.Included')
import Python.Included as pyInc
path_py3_lib = pyInc.Installer.EmbeddedPythonHome
sys.path.append(path_py3_lib + r'\Lib')
sys.path.append(path_py3_lib + r'\Lib\site-packages')

import numpy as np

data, search_value, replace_value = IN

array_3d = np.array(data).astype(object)
array_3d[array_3d == search_value] = replace_value

OUT = array_3d.tolist()

or in pure Python (input list need not be homogeneous)

import sys

def convert_value(value):
    global search_value
    global replace_value
    return replace_value if value == search_value else value

def nestedRecursFunc(lst, functoApply):
    newlst = list(lst)[:] # copy input list and convert it (if necessary)
    for idx, elem in enumerate(lst):
        if isinstance(elem, list) and len(elem) > 0:
            newlst[idx] = nestedRecursFunc(lst[idx], functoApply)
        elif isinstance(elem, list) and len(elem) == 0:
            newlst[idx] = []
        else:
            newlst[idx] = convert_value(lst[idx])

    return newlst
    
data, search_value, replace_value = IN 

OUT = nestedRecursFunc(data, convert_value)
4 Likes