【问题标题】:Use replace function with list of strings python?使用带有字符串列表的替换函数python?
【发布时间】:2021-11-19 16:37:11
【问题描述】:

我有一堆替换函数来修改我拥有的字符串列表。最初,我已经写出了我想要替换的字符串的每个列表理解。

ls = ['sentence with string a', 'sentence with string d and string a', 
      'sentence with string d', 'sentence with string b and string b again',
      'sentence with string c', 'sentence with string c and string d']

ls = [x.replace('string a' , '') for x in ls]
ls = [x.replace('string b' , '') for x in ls]
ls = [x.replace('string c' , '') for x in ls]
ls = [x.replace('string d' , '') for x in ls]

ls = ['sentence with', 'sentence with and', 
      'sentence with', 'sentence with and again',
      'sentence with', 'sentence with and']

但是,由于我要替换的字符串可能会更改,因此我想使用列表来执行所有替换功能。当我尝试 for 循环时,这最终会从字符串中间删除字符,并且不会像以前那样给我列表。

words = ['string a', 'string b', 'string c', 'string d']

for txt in words:
        ls = [x.replace(txt, "") for x in ls]

如何使用字符串列表来获得相同的结果?

【问题讨论】:

  • 从混乱的语法突出显示中可以看出,您的代码似乎没有意义。
  • 您在words = [ 末尾缺少]
  • 除了那个错字,它看起来应该可以工作。
  • 您在第一个代码块中缺少一堆 ' 字符。 x.replace('string a' , ') 应该是 x.replace('string a' , '')
  • 为什么不使用推导式?

标签: python list-comprehension


【解决方案1】:

你可以使用推导式和functools.reduce:

from functools import reduce

words = ['string a', 'string b', 'string c', 'string d']

ls = ['sentence with string a', 'sentence with string d and string a', 
      'sentence with string d', 'sentence with string b and string b again',
      'sentence with string c', 'sentence with string c and string d']


[reduce(lambda s, w: s.replace(w, ""), words, sent) for sent in ls]
# ['sentence with ', 'sentence with  and ', 'sentence with ', 
#  'sentence with  and  again', 'sentence with ', 'sentence with  and ']

【讨论】:

    【解决方案2】:

    使用re

    reg = re.compile('string [abcd]')
    

    然后你可以在理解中使用编译的正则表达式:

    [reg.sub('', s) for s in ls]
    

    结果:

    ['sentence with ',
     'sentence with  and ',
     'sentence with ',
     'sentence with  and  again',
     'sentence with ',
     'sentence with  and ']
    

    【讨论】:

      【解决方案3】:

      似乎 Jab 比我快,但如果你想让你的单词列表更灵活,这里有一个类似的解决方案:

      import re
      
      pattern = '|'.join(words)
      [re.sub(pattern , '', x).strip() for x in ls]
      

      结果

      ['sentence with',
       'sentence with  and',
       'sentence with',
       'sentence with  and  again',
       'sentence with',
       'sentence with  and']
      

      【讨论】:

        猜你喜欢
        • 2019-02-16
        • 1970-01-01
        • 2016-07-01
        • 1970-01-01
        • 2019-01-30
        • 2019-06-06
        • 2019-02-26
        • 2021-06-17
        • 2010-10-20
        相关资源
        最近更新 更多