【问题标题】:Replace a string in list of lists替换列表列表中的字符串
【发布时间】:2012-11-26 17:42:11
【问题描述】:

我有一个字符串列表,例如:

example = [["string 1", "a\r\ntest string:"],["string 1", "test 2: another\r\ntest string"]]

我想用空格替换"\r\n"(并在所有字符串的末尾去掉":")。

对于一个普通的列表,我会使用列表推导来删除或替换类似的项目

example = [x.replace('\r\n','') for x in example]

甚至是 lambda 函数

map(lambda x: str.replace(x, '\r\n', ''),example)

但我无法让它适用于嵌套列表。有什么建议吗?

【问题讨论】:

    标签: python list python-3.x replace nested-lists


    【解决方案1】:

    以下示例,在列表列表(子列表)之间进行迭代,以替换字符串、单词。

    myoldlist=[['aa bbbbb'],['dd myword'],['aa myword']]
    mynewlist=[]
    for i in xrange(0,3,1):
        mynewlist.append([x.replace('myword', 'new_word') for x in myoldlist[i]])
    
    print mynewlist
    # ['aa bbbbb'],['dd new_word'],['aa new_word']
    

    【讨论】:

      【解决方案2】:

      如果您的列表比您给出的示例更复杂,例如,如果它们具有三层嵌套,则以下将遍历列表及其所有子列表,将 \r\n 替换为空格在它遇到的任何字符串中。

      def replace_chars(s):
          return s.replace('\r\n', ' ')
      
      def recursively_apply(l, f):
          for n, i in enumerate(l):
              if type(i) is list:
                  l[n] = recursively_apply(l[n], f)
              elif type(i) is str:
                  l[n] = f(i)
          return l
      example = [[["dsfasdf", "another\r\ntest extra embedded"], 
               "ans a \r\n string here"],
              ['another \r\nlist'], "and \r\n another string"]
      print recursively_apply(example, replace_chars)
      

      【讨论】:

        【解决方案3】:

        好吧,想想你的原始代码在做什么:

        example = [x.replace('\r\n','') for x in example]
        

        您正在对列表的每个元素使用.replace() 方法,就好像它是一个字符串一样。但是这个列表的每个元素都是另一个列表!您不想在子列表上调用.replace(),而是想在其每个内容上调用它。

        对于嵌套列表,使用嵌套列表推导!

        example = [["string 1", "a\r\ntest string:"],["string 1", "test 2: another\r\ntest string"]]
        example = [[x.replace('\r\n','') for x in l] for l in example]
        print example
        

        [['string 1', 'atest string:'], ['string 1', 'test 2: anothertest string']]
        

        【讨论】:

        • 谢谢,我刚开始学习 python,但在任何地方都找不到像样的例子。我设法让它在我的程序中工作。我看到我试图调用示例两次,例如:for x in example] for l in example]
        • 如果我不知道该列表嵌套了多少,我想全部替换怎么办?
        【解决方案4】:
        example = [[x.replace('\r\n','') for x in i] for i in example]
        

        【讨论】:

        • 很高兴能解释一下发生了什么。
        猜你喜欢
        • 2019-02-26
        • 2021-05-22
        • 1970-01-01
        • 2013-05-01
        • 2017-06-22
        • 1970-01-01
        • 2013-11-15
        • 2019-01-30
        • 2010-10-20
        相关资源
        最近更新 更多