是否有类似.replace()的方法用于python中的列表? [英] Is there a method like .replace() for list in python?
问题描述
我使用.split()方法从字符串中列出了一个列表.例如:string =我喜欢鸡肉",我将使用.split()在字符串 ['I','like','chicken']
中列出单词列表现在,如果我想用其他东西代替鸡肉",我可以使用哪种方法,例如.replace(),但要使用列表?
i've made a list out of a string using .split() method.
For example: string = " I like chicken" i will use .split() to make a list of words in the string ['I','like','chicken']
Now if i want to replace 'chicken' with something else, what method i can use that is like .replace() but for a list?
推荐答案
没有内置功能,但这只是循环进行就地替换:
There’s nothing built-in, but it’s just a loop to do the replacement in-place:
for i, word in enumerate(words):
if word == 'chicken':
words[i] = 'broccoli'
或较短的选项(如果始终只有一个实例):
or a shorter option if there’s always exactly one instance:
words[words.index('chicken')] = 'broccoli'
或列表理解以创建新列表:
or a list comprehension to create a new list:
new_words = ['broccoli' if word == 'chicken' else word for word in words]
其中任何一个都可以包装成一个函数:
any of which can be wrapped up in a function:
def replaced(sequence, old, new):
return (new if x == old else x for x in sequence)
new_words = list(replaced(words, 'chicken', 'broccoli'))
这篇关于是否有类似.replace()的方法用于python中的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!