python中的列表有没有像.replace()这样的方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43107251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:31:49  来源:igfitidea点击:

Is there a method like .replace() for list in python?

pythonstringlistmethods

提问by Patrick Tran

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?

我已经使用 .split() 方法从字符串中创建了一个列表。例如: string = "I like chicken" 我将使用 .split() 来制作字符串中的单词列表['I','like','chicken']现在如果我想用其他东西替换 'chicken',我可以使用什么方法就像 .replace( ) 但对于一个列表?

回答by Ry-

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

回答by ShadowRanger

No such method exists, but a list comprehension can be adapted to the purpose easily, no new methods on listneeded:

不存在这样的方法,但是列表理解可以很容易地适应这个目的,不需要新的方法list

words = 'I like chicken'.split()
replaced = ['turkey' if wd == "chicken" else wd for wd in words]
print(replaced)

Which outputs: ['I', 'like', 'turkey']

哪些输出: ['I', 'like', 'turkey']