【问题标题】:Replacing several strings in a list in a single statement在单个语句中替换列表中的多个字符串
【发布时间】:2019-07-23 17:05:59
【问题描述】:

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

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

【问题讨论】:

    标签: python python-3.x list replace


    【解决方案1】:

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

    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 用于将"Will" 替换为"Morris"

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

    【讨论】:

    • 感谢您的解释
    【解决方案2】:

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

    【讨论】:

      【解决方案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]
      

      【讨论】:

      • 更简单:[replacements.get(f, f) for f in friends]
      • 好点@pault - 我想过使用.get,但由于某种原因没有考虑提供原件作为默认值:-)
      • 谢谢你的回答我的问题是它不在一个单一的声明中:/
      • 我想使用字典,但最终使用了两个语句
      • 为什么必须在一个语句中完成? (您可以通过不将 replacemens 定义为变量并将其用作理解中的文字值来将其变成一条语句 - 但那将是一条长线,难以阅读,因此不推荐。)
      猜你喜欢
      • 2016-03-01
      • 2020-05-30
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 2019-10-04
      • 2014-11-12
      • 2019-08-04
      相关资源
      最近更新 更多