【问题标题】:How can I subtract 2 string or list in python?如何在 python 中减去 2 个字符串或列表?
【发布时间】:2017-12-26 10:04:15
【问题描述】:

我的代码中有非常大的字符串。我想检测字符串之间的不同字符。这是我的意思的一个例子:

 a='ababaab'
 b='abaaaaa'
 a=a-b
 print(a)

我希望是这样的; 'bb' 或 '000b00b'

我知道这听起来很奇怪,但我真的需要这个。

【问题讨论】:

  • 所以你想要a 中所有在b 中相同位置不同的字符?

标签: python string list difference subtraction


【解决方案1】:

你可以这样做:

a = 'ababaab'
b = 'abaaaaa'

a = ''.join(x if x != y else '0' for x, y in zip(a, b))
# '000b00b'
# OR
a = ''.join(x for x, y in zip(a, b) if x != y)
# 'bb'

【讨论】:

    【解决方案2】:

    这是一个例子:它适用于列表

    listA = ["a","b"]
    listB = ["b", "c"]
    listC = [item for item in listB if item not in listA]
    print listC
    

    输出

    # ['c']
    

    【讨论】:

      【解决方案3】:

      您可以创建如下自定义函数: (假设两个字符串的长度相等)

      def str_substract(str1, str2):
          res = ""
          for _ in xrange(len(str1)):
              if str1[_] != str2[_]:
                  res += str1[_]
              else:
                  res += "0"
          return res
      
      a='ababaab'
      b='abaaaaa'
      
      print str_substract(a, b)
      

      输出:

      000b00b
      

      【讨论】:

      • xrange 使用了哪个库?
      • 为什么你使用_ 作为循环变量,而它通常用于throw-away 变量?此外,这将非常效率低下,使用 +=str 对象会给你二次复杂度。
      • @VuralErdogan 它是 Python 2 等价于 Python 3 range
      【解决方案4】:
      result = ''
      
      for temp in a:
          result += temp if temp not in b else '0'
      

      【讨论】:

      • 虽然这段代码 sn-p 可以解决问题,including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
      【解决方案5】:

      使用zip:

      res = ''
      for i, j in zip(a, b):
           if i == j:
               res += '0'
           else:
               res += i
      

      使用列表存储结果可能更有效。

      【讨论】:

        【解决方案6】:

        如果你想要s1 - s2

           s1 = 'ababaab'
            s2 = 'abaaaaa'
        
        
        
           for i,j in zip(s1,s2):
                if (i != j):
                    print i,
        

        输出:bb

        【讨论】:

          猜你喜欢
          • 2019-07-27
          • 2016-07-10
          • 1970-01-01
          • 1970-01-01
          • 2021-03-17
          • 2016-05-13
          • 1970-01-01
          • 1970-01-01
          • 2017-09-29
          相关资源
          最近更新 更多