2024-04-19 03:27:32 发布
网友
我试图在一个语句中用两个不同的单词替换这个列表中的第三个和第四个单词,但似乎找不到这样做的方法,我尝试的方法与错误AttributeError: 'list' object has no attribute 'replace'不起作用:
AttributeError: 'list' object has no attribute 'replace'
friends = ["Lola", "Loic", "Rene", "Will", "Seb"] friends.replace("Rene", "Jack").replace("Will", "Morris")
如果要进行多次替换,最简单的方法可能是将要替换的内容编成字典:
replacements = {"Rene": "Jack", "Will": "Morris"}
然后使用列表理解:
friends = [replacements[friend] if friend in replacements else friend for friend in friends]
或者更简洁地说,使用带有默认值的dict.get()。你知道吗
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
"Morris"
"Will"
外map中的lambda用于将"Rene"替换为"Jack"
"Rene"
"Jack"
另一种方法是,如果您不介意将列表转换为pandas.Series的开销:
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']
如果要进行多次替换,最简单的方法可能是将要替换的内容编成字典:
然后使用列表理解:
或者更简洁地说,使用带有默认值的
dict.get()
。你知道吗这不是一个很好的解决方案,但是一行:
简要说明:
它是一个“map(lambda,list)”解决方案,其输出列表作为输入列表传递给另一个外部“map(lambda,list)”解决方案。你知道吗
内部
map
中的lambda
用于用"Morris"
替换"Will"
。你知道吗外
map
中的lambda
用于将"Rene"
替换为"Jack"
另一种方法是,如果您不介意将列表转换为
pandas.Series
的开销:相关问题 更多 >
编程相关推荐