hhp*_*arr 0 python replace list python-3.x
我试图用一个单独的语句中的两个不同的单词替换此列表中的第三个和第四个单词,并且似乎无法找到我尝试过的不能与错误一起使用的单词AttributeError: 'list' object has no attribute 'replace':
friends = ["Lola", "Loic", "Rene", "Will", "Seb"]
friends.replace("Rene", "Jack").replace("Will", "Morris")
Run Code Online (Sandbox Code Playgroud)
如果你想做多次替换可能最简单的方法是制作一个你要用什么替换的字典:
replacements = {"Rene": "Jack", "Will": "Morris"}
Run Code Online (Sandbox Code Playgroud)
然后使用列表理解:
friends = [replacements[friend] if friend in replacements else friend for friend in friends]
Run Code Online (Sandbox Code Playgroud)
或者更紧凑,使用dict.get()默认值.
friends = [replacements.get(friend, friend) for friend in friends]
Run Code Online (Sandbox Code Playgroud)