【问题标题】:How do you replace certain parts of specific elements of lists?你如何替换列表中特定元素的某些部分?
【发布时间】:2018-02-22 16:36:11
【问题描述】:

您将如何替换列表中某些项目的一部分? (Python 3.x) 假设我有一个列表:

x = ["part2keep removeMe", "saveme removeMe", "third length to throw it off removeMe", "element to save", "KeepThisPart"]

如果我只想删除“removeMe”部分,你会怎么做?到目前为止我有这个:

def replaceExampleA(x, y):
    for i in x:
        if i[len(i)-8:len(i)-1] == "removeMe":
            y.append(i[0: -12])
        else:
            y.append(i)

编辑:刚刚意识到我犯了一个错误 - 列表更像是这样的: x = ["part2keep removeMe 123", "saveme removeMe 12", "third length to throw it off removeMe 83", "element to save", "KeepThisPart"]

我还需要使用“removeMe”从元素中删除数字。谢谢

【问题讨论】:

    标签: python arrays string python-3.x list


    【解决方案1】:
    x = [s.replace('removeMe', '') for s in x]
    

    【讨论】:

      【解决方案2】:

      这可以通过列表理解来完成

      x = ["part2keep removeMe", "saveme removeMe", "third length to throw it off removeMe"]
      
      print(y.replace(' removeMe', '') for y in x)
      

      【讨论】:

        【解决方案3】:

        您可以使用正则表达式来确保代码始终剥离removeMe,仅当它出现在字符串末尾时:

        import re
        x = ["part2keep removeMe", "saveme removeMe", "third length to throw it off removeMe", "element to save", "KeepThisPart"]
        new_x = [re.sub('\sremoveMe$', '', i) for i in x]
        

        输出:

        ['part2keep', 'saveme', 'third length to throw it off', 'element to save', 'KeepThisPart']
        

        【讨论】:

          【解决方案4】:

          你也可以使用map函数

          new_x = map(lambda e: e.replace('removeMe', ''), x)
          

          这样做的好处是你可以得到一个生成器。所以在某些情况下,这会提高内存效率。如果你想要一个列表,就像其他答案一样,那么你需要将它转换回一个列表

          new_x = list(new_x)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-01-03
            • 2015-12-29
            • 2020-09-27
            • 2018-05-06
            • 1970-01-01
            • 2019-09-17
            • 2021-02-19
            • 2015-03-03
            相关资源
            最近更新 更多