在一个州替换列表中的几个字符串

2024-04-19 03:27:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: 方法no列表object错误attribute语句单词
3条回答

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

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]

这不是一个很好的解决方案,但是一行:

friends = list(map(lambda x: x if x != "Will" else "Morris", map(lambda x: x if x != "Rene" else "Jack", friends)))

简要说明:

它是一个“map(lambda,list)”解决方案,其输出列表作为输入列表传递给另一个外部“map(lambda,list)”解决方案。你知道吗

内部map中的lambda用于用"Morris"替换"Will"。你知道吗

map中的lambda用于将"Rene"替换为"Jack"

另一种方法是,如果您不介意将列表转换为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']

相关问题 更多 >