函数replace_list(list_1,value1,value2),其中value1必须由list_1中的value2替换

时间:2018-11-28 12:26:38

标签: python

我很难弄清楚这一点。我正在尝试制作一个函数replace_list(list_1,value1,value2),其中value1必须由list_1中的value2替换。它应该看起来像这样:

>>> list_1 = [[[7]], 8]

>>> print(replacing_list(list_1, 7, 'a'))

[[['a']], 8]

>>> list_1

[[[7]], 8]

>>> print(replacing_list([1, 2, 3, [1, 2], 3, [[[1]]], [], 2], 1, 'x'))

['x', 2, 3, ['x', 2], 3, [[['x']]], [], 2]

>>> print(replacing_list([3, [33, [333, [13], 13]], 36], 3, 'q'))

['q', [33, [333, [13], 13]], 36]

>>> print(replacing_list([3, [33, [333, [13], 13]], 36], [13], 'm'))

[3, [33, [333, 'm', 13]], 36]

有人可以帮我吗?

2 个答案:

答案 0 :(得分:0)

我正在明确测试类型;但我认为可以有更好的方法。但是,它正在处理列表。这是递归。

def rep(l,v1,v2):
    for i,j in enumerate(l):
        if j == v1:
            l[i] = v2
        if type(j) == list:
            l[i] = rep(l[i],v1,v2)
    return l

>>> rep([3, [33, [333, [13], 13]], 36], [13], 'm')
[3, [33, [333, 'm', 13]], 36]

答案 1 :(得分:0)

您可以这样做:

def replacing_list(lst, to_replace, replacement):
    result = []
    for e in lst:
        if e == to_replace:
            result.append(replacement)
        elif isinstance(e, list):
            result.append(replacing_list(e, to_replace, replacement))
        else:
            result.append(e)
    return result


print(replacing_list([[[7]], 8], 7, 'a'))
print(replacing_list([1, 2, 3, [1, 2], 3, [[[1]]], [], 2], 1, 'x'))
print(replacing_list([3, [33, [333, [13], 13]], 36], 3, 'q'))
print(replacing_list([3, [33, [333, [13], 13]], 36], [13], 'm'))

输出

[[['a']], 8]
['x', 2, 3, ['x', 2], 3, [[['x']]], [], 2]
['q', [33, [333, [13], 13]], 36]
[3, [33, [333, 'm', 13]], 36]

请注意,replacing_list不会更改原始列表。