简体   繁体   中英

How to replace a word to another word in a list python?

If I have this list:

['hello', 'world', 'goodbye', 'world', 'food']

Is it possible to replace every world to any other word without using any auto command, I am thinking about something like this:

if 'world' in list:
    'world' in list == 'peace'

You can use a list comprehension with an if-else.

list_A = ['hello', 'world', 'goodbye', 'world']
list_B = [word if word != 'world' else 'friend' for word in list_A]

You now have a new list, list_B , where all instances of the word "world" have been replaced with "friend".

I don't think there is an out of the box solution eg something like my_list.replace() that you are looking for. Thus, the simple solution is just to iterate through the entire list (using enumerate to preserve the iterative variable).

Try this:

for index, elem in enumerate(my_list):
    if elem == "world":
        my_list[index] = "peace"

This is an expanded view of what is happening in Zach's answer

word_list = ['hello', 'world', 'goodbye', 'world', 'food']
for ndx, word in enumerate(word_list):
    if word == 'world':
        word_list[ndx] = 'peace'
print word_list
# result: ['hello', 'peace', 'goodbye', 'peace', 'food']

I don't know if i understand your question, but it should work:

lst = ['hello', 'world', 'goodbye', 'world', 'food']

lst = [i.replace('world', 'peace') for i in lst]

print(lst2)

" If " statement isn't needed. Cause if ' world ' not exist, it will just ignore it

Although there isn't any list.replace() method in the python standard library.

But this utility function may help you:

def replace(l, target_word, replaced_word):
    for index, element in enumerate(l):
        if element == target_word:
            l[index] = replaced_word

    return l
def customReplaceFunction(wordList, replacingWord):
    for i in range(len(wordList)):
        if wordList[i] == 'world':
            wordList[i] = replacingWord
    print wordList

Iterate over list and replace "world" with "peace"

wordlist = ['hello', 'world', 'goodbye', 'world', 'food']


for i in range(0,len(wordlist)):
   if wordlist[i]=="world":
      wordlist[i]="peace"
print(wordlist) 

wordlist = ['hello', 'peace', 'goodbye', 'peace', 'food']  

You can map over each world and replace with a suitable word.

Using a lambda function,

words = map(lambda word: word.replace('world', 'peace') , l)

如果您的列表中有唯一值:

my_list[my_list.index('old_word')]='new_word' 

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