在单个语句中替换列表中的几个字符串

时间:2019-03-01 16:16:24

标签: python python-3.x list replace

我试图在一个语句中用两个不同的单词替换此列表的第三和第四个单词,但是似乎找不到做到这一点的方法,我尝试的错误AttributeError: 'list' object has no attribute 'replace'不起作用:

friends = ["Lola", "Loic", "Rene", "Will", "Seb"]
friends.replace("Rene", "Jack").replace("Will", "Morris")

3 个答案:

答案 0 :(得分:8)

如果要进行多次替换,最简单的方法可能是将要替换的内容制作成字典:

replacements = {"Rene": "Jack", "Will": "Morris"}

,然后使用列表理解:

friends = [replacements[friend] if friend in replacements else friend for friend in friends]

或更紧凑地说,使用具有默认值的dict.get()

friends = [replacements.get(friend, friend) for friend in friends]

答案 1 :(得分:1)

另一种方式,如果您不介意将列表转换为pandas.Series的开销:

import pandas as pd

friends = ["Lola", "Loic", "Rene", "Will", "Seb"]

friends = pd.Series(friends).replace(to_replace={"Rene":"Jack", "Will":"Morris"}).tolist()
print(friends)
#['Lola', 'Loic', 'Jack', 'Morris', 'Seb']

答案 2 :(得分:0)

这不是一个很漂亮的解决方案,但是还是单线的:

deleteEvent(eventId:number): Observable<{}> {
        console.log(eventId, 'number');
        return this.http.delete<ModelEvent>(environment.baseUrl+`Calendar/${eventId}`)
        .pipe(
            tap(data => console.log('res', eventId)), //not consoles..!?
            catchError(this.handleError)
        )
    }

简要说明:

这是一个“ map(lambda,list)”解决方案,其输出列表作为输入列表传递到另一个外部“ map(lambda,list)”解决方案。

内部friends = list(map(lambda x: x if x != "Will" else "Morris", map(lambda x: x if x != "Rene" else "Jack", friends))) 中的lambda用于将map替换为"Will"

外部"Morris"中的lambda用于将map替换为"Rene"