简体   繁体   English

将 y 的实例更改为 x 中的 z(其中 x 是一个列表)

[英]Change instance of y to z in x(where x is a list)

I wrote a function that changes all instances of y to z in x (where x is a list) but somehow my code is not working.我写了一个 function 将 x 中 y 的所有实例更改为 z (其中 x 是一个列表),但不知何故我的代码不起作用。 The outcome should have been [1, 'zzz', 3, 1, 'zzz', 3].结果应该是 [1, 'zzz', 3, 1, 'zzz', 3]。 I attached my code below any help is appreciated.我在下面附上了我的代码,感谢您的帮助。 Thanks in advance.提前致谢。

x = [1, 2, 3, 1, 2, 3]

def changeThem(x,y,z):
    replace = {y : z}
    for key, value in replace.items():
        x = x.replace(key, value)
    print(x)
changeThem(x,2,'zzz')

A list does not have .replace() method.列表没有.replace()方法。 How about the following?下面的呢?

x = [1, 2, 3, 1, 2, 3]

def changeThem(x,y,z):
    return [z if i == y else i for i in x]

print(changeThem(x, 2, 'zz'))

The function consists of just one line so defining this function might not be even necessary. function 仅包含一行,因此可能甚至不需要定义此 function。 But I am leaving it in case you would like to call it multiple times.但我会留下它,以防你想多次调用它。

Your code yields an AttributeError .您的代码产生一个AttributeError This is because list does not have a replace method.这是因为list没有replace方法。 str has a replace method, so this might be where you're getting confused. str有一个replace方法,所以这可能是你感到困惑的地方。

You could accomplish this with a very simple list comprehension:您可以通过非常简单的列表理解来完成此操作:

x = [z if e == y else e for e in x]

Essentially, the above list comprehension states:本质上,上述列表理解状态:

For every value e in the list x, replace it with z if the element is equal to y.对于列表 x 中的每个值 e,如果元素等于 y,则将其替换为 z。 Otherwise, just keep the element there.否则,只需将元素保留在那里。

It is also equivalent to the following:它也等价于以下内容:

result = []
for e in x:
    if e == y:
        result.append(z)
    else:
        result.append(x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM