【问题标题】:Find and replace string values in list查找和替换列表中的字符串值
【发布时间】:2011-03-09 09:05:22
【问题描述】:

我得到了这份清单:

words = ['how', 'much', 'is[br]', 'the', 'fish[br]', 'no', 'really']

我想要的是用一些类似于<br /> 的奇妙值替换[br],从而获得一个新列表:

words = ['how', 'much', 'is<br />', 'the', 'fish<br />', 'no', 'really']

【问题讨论】:

    标签: python string list


    【解决方案1】:
    words = [w.replace('[br]', '<br />') for w in words]
    

    这些被称为List Comprehensions

    【讨论】:

    • 比较这个列表理解方法和 map 方法(由@Anthony Kong 发布),这个列表方法大约快 2 倍。它还允许在同一个调用中插入多个替换,例如resname = [name.replace('DA', 'ADE').replace('DC', 'CYT').replace('DG', 'GUA').replace('DT', 'THY') for name in ncp.resname()]
    • @sberry 我有一个列表['word STRING', 'word_count BIGINT', 'corpus STRING', 'corpus_date BIGINT'],我试图用空替换',但这不起作用。我们如何用这个替换它?
    • 如果其中一项是浮点数/整数怎么办?
    【解决方案2】:

    你可以使用,例如:

    words = [word.replace('[br]','<br />') for word in words]
    

    【讨论】:

    • @macetw 其实是第一个答案。
    • 看时间戳似乎他们都同时回答了,也许这个迟到了几分之一秒......
    【解决方案3】:

    除了列表理解,你可以试试ma​​p

    >>> map(lambda x: str.replace(x, "[br]", "<br/>"), words)
    ['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']
    

    【讨论】:

      【解决方案4】:

      如果您想了解不同方法的性能,这里有一些时间安排:

      In [1]: words = [str(i) for i in range(10000)]
      
      In [2]: %timeit replaced = [w.replace('1', '<1>') for w in words]
      100 loops, best of 3: 2.98 ms per loop
      
      In [3]: %timeit replaced = map(lambda x: str.replace(x, '1', '<1>'), words)
      100 loops, best of 3: 5.09 ms per loop
      
      In [4]: %timeit replaced = map(lambda x: x.replace('1', '<1>'), words)
      100 loops, best of 3: 4.39 ms per loop
      
      In [5]: import re
      
      In [6]: r = re.compile('1')
      
      In [7]: %timeit replaced = [r.sub('<1>', w) for w in words]
      100 loops, best of 3: 6.15 ms per loop
      

      正如您所见,对于这种简单的模式,可接受的列表理解是最快的,但请看以下内容:

      In [8]: %timeit replaced = [w.replace('1', '<1>').replace('324', '<324>').replace('567', '<567>') for w in words]
      100 loops, best of 3: 8.25 ms per loop
      
      In [9]: r = re.compile('(1|324|567)')
      
      In [10]: %timeit replaced = [r.sub('<\1>', w) for w in words]
      100 loops, best of 3: 7.87 ms per loop
      

      这表明对于更复杂的替换,预编译的正则表达式(如9-10)可以(快得多)。这实际上取决于您的问题和 reg-exp 的最短部分。

      【讨论】:

        【解决方案5】:

        for 循环的示例(我更喜欢 List Comprehensions)。

        a, b = '[br]', '<br />'
        for i, v in enumerate(words):
            if a in v:
                words[i] = v.replace(a, b)
        print(words)
        # ['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-01-03
          • 2016-01-20
          • 1970-01-01
          • 2011-08-22
          • 1970-01-01
          • 2013-08-31
          相关资源
          最近更新 更多