代码之家  ›  专栏  ›  技术社区  ›  Eric Herlitz

在Python列表中查找和替换字符串值

  •  112
  • Eric Herlitz  · 技术社区  · 14 年前

    我有一张单子:

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

    [br] 具有类似于 <br />

    words = ['how', 'much', 'is<br />', 'the', 'fish<br />', 'no', 'really']
    
    4 回复  |  直到 5 年前
        1
  •  308
  •   Teymour Steve K    5 年前
    words = [w.replace('[br]', '<br />') for w in words]
    

    这些被称为 List Comprehensions

        2
  •  36
  •   houbysoft    14 年前

    words = [word.replace('[br]','<br />') for word in words]
    
        3
  •  34
  •   Anthony Kong    14 年前

    除了列表理解,你还可以试试 地图

    >>> map(lambda x: str.replace(x, "[br]", "<br/>"), words)
    ['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']
    
        4
  •  17
  •   Jörn Hees    8 年前

    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
    

    这表明对于更复杂的替换,预编译的reg exp(如 9-10 )可以更快。这真的取决于你的问题和最短的一部分的reg-exp。

        5
  •  3
  •   Waket Zheng    5 年前

    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']