简体   繁体   中英

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. The outcome should have been [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. 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. But I am leaving it in case you would like to call it multiple times.

Your code yields an AttributeError . This is because list does not have a replace method. str has a replace method, so this might be where you're getting confused.

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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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