【问题标题】:How to use list comprehensions to replace characters in a string?如何使用列表推导替换字符串中的字符?
【发布时间】:2019-07-19 16:55:03
【问题描述】:

假设我有一个字符串列表,例如'12hell0',我想将其剥离为'hello'。 我的想法是:

words = ['12hell0','123word', ...]
for word in words:
   stripped = ''.join([i for i in word if not i.isdigit()]

我知道这会产生“地狱”,有没有办法使用检查它是否为“0”然后替换为“o”?不知道如何用多个条件构建理解,但使用常规语句会是这样的:

for word in words:
    stripped = ''
    word.replace('0','o')
    for char in word:
        if not char.isdigit():
           stripped+=char

感谢您的帮助或指导!

【问题讨论】:

  • 预期输出是什么?是['hello', 'word'] 吗?
  • @DeveshKumarSingh 是的。
  • @DeveshKumarSingh 感谢您的回答,但所选答案的格式可以解决我试图自己解决的问题。

标签: python list-comprehension


【解决方案1】:

你可以这样做:

words = ['12hell0','123word', ...]
new_words = [] # This will receive the changed words

for word in words: # Iterating through array elements
    # This will store the new word.
    new_word = ''.join([ch.replace('0', 'o') for ch in word if not ch.isdigit() or ch == '0'])
    new_words.append(new_word)
print(new_words)

注意:这可能不是很pythonic。我建议使用分离的方法,而不是这种方式。代码必须清晰易读,这样会使其他开发人员更难进行维护。

列表理解很棒,但要小心。

【讨论】:

  • 这对我来说很有意义。谢谢!
【解决方案2】:

如果您真的想让代码看起来不太容易理解(双关语),您可以单行执行:

"".join(['o' if i == '0' else i for i in "123hell0" if not i.isdigit() or i=='0'])

我们可以分解它: 'o' if i == '0' else i - 将 '0' 替换为 'o'

额外条件...or i=='0' 将使其取零,尽管是数字。

【讨论】:

    【解决方案3】:

    我认为你在正确的轨道上,仅使用列表理解可能会变得不可读,在这种情况下,将替换逻辑拆分为一个函数可能是最清晰的解决方案。这样您就可以应用更多逻辑或稍后改变主意,而不必打扰您的代码。

    def replaceDigits(word):
        stripped = ""
        for char in word:
            if char == "0":
                stripped += "o"
            elif not char.isdigit():
                stripped += char
        return stripped
    
    
    words = ['12hell0', '123word']
    stripped = [replaceDigits(n) for n in words]
    print(stripped)
    

    【讨论】:

      【解决方案4】:

      您可以编写一些 transform() 函数,将所有子字符串替换为您打算为表面结构生成的字符串,仅当您的布尔值为 True 时才将其应用于 i:

      stripped = ''.join([transform(i) for i in word if not i.isdigit()]
      

      在列表理解中嵌套条件是不可能的, 因此,如果需要,请使用循环。

      【讨论】:

        【解决方案5】:

        对于i == '0':

        的情况,您可以在列表理解中添加另一个 if else
        words =['12hell0','123word']
        new_words = []
        for word in words:
          stripped = ''.join([i if not i.isdigit() else 'o' if i == '0' else '' for i in word])
          new_words.append(stripped)
        print(new_words)
        

        输出:

        ['hello', 'word']
        

        【讨论】:

          【解决方案6】:

          这是通过列表理解来实现的一种方法,尽管我建议不要这样做,因为它最终不太可读。

          我们遍历单词列表,对于每个单词,如果我们找到'0',我们会使用字符'o',如果我们找到任何其他数字,我们会使用一个空字符'',如果我们找到任何其他数字,我们会使用字符本身案例,并加入所有通过str.join

          words = ['12hell0','123word']
          words = [''.join('o' if c == '0' else '' if c.isdigit() else c for c in word) for word in words]
          print(words)
          

          输出将是

          ['hello', 'word']
          

          【讨论】:

            【解决方案7】:

            您可以在 python 中使用正则表达式库。模式 '[^\d]+' 搜索一组连续的非数字字符。

            • ^: 非
            • \d: 数字
            • []:单个字符
            • +:出现一次或多次

            代码:

            import re
            words = ['12hell0','123word']
            new_words = [word.replace('0','o') for word in words]
            stripped = [re.search('[^\d]+',word).group() if re.search('[^\d]+',word) else '' for word in new_words]
            

            输出:['hello', 'word']

            【讨论】:

              【解决方案8】:

              这里是函数式编程方式:

              f = lambda arg: list(
                  map(
                       lambda i: "".join(filter(
                           lambda j: j.isalpha(), i.replace("0", "o"))
                       ), arg
                  )
              )
              
              words = ['12hell0','123word']
              print(f(words))
              # ['hello', 'word']
              

              【讨论】:

                【解决方案9】:

                试试这个,

                >>> words =['12hell0','123word']
                >>> [''.join(character for character in word.replace('0', 'o') if not character.isdigit()) for word in words]
                ['hello', 'word']
                

                【讨论】:

                  猜你喜欢
                  • 2020-06-03
                  • 2022-01-02
                  • 2013-05-01
                  • 2019-06-26
                  • 2021-05-22
                  • 2019-05-13
                  • 1970-01-01
                  • 2016-09-02
                  • 1970-01-01
                  相关资源
                  最近更新 更多