[英]How to replace a word to another word in a list python?
如果我有这个清单:
['hello', 'world', 'goodbye', 'world', 'food']
是否可以在不使用任何自动命令的情况下将每个world
替换为任何其他单词,我正在考虑这样的事情:
if 'world' in list:
'world' in list == 'peace'
您可以使用带有 if-else 的列表推导式。
list_A = ['hello', 'world', 'goodbye', 'world']
list_B = [word if word != 'world' else 'friend' for word in list_A]
您现在有一个新列表list_B
,其中“world”一词的所有实例都已替换为“friend”。
我认为没有开箱即用的解决方案,例如您正在寻找的类似 my_list.replace() 的解决方案。 因此,简单的解决方案就是遍历整个列表(使用 enumerate 保留迭代变量)。
试试这个:
for index, elem in enumerate(my_list):
if elem == "world":
my_list[index] = "peace"
这是 Zach 回答中发生的事情的扩展视图
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']
我不知道我是否理解你的问题,但它应该有效:
lst = ['hello', 'world', 'goodbye', 'world', 'food']
lst = [i.replace('world', 'peace') for i in lst]
print(lst2)
不需要“如果”语句。 因为如果“世界”不存在,它会忽略它
尽管 python 标准库中没有任何list.replace()
方法。
但是这个效用函数可以帮助你:
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
迭代列表并将“世界”替换为“和平”
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']
您可以映射每个世界并替换为合适的单词。
使用 lambda 函数,
words = map(lambda word: word.replace('world', 'peace') , l)
如果您的列表中有唯一值:
my_list[my_list.index('old_word')]='new_word'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.