【问题标题】:Python: Replace ith occurence of x with ith element in listPython:用列表中的第 i 个元素替换第 n 次出现的 x
【发布时间】:2011-08-27 08:39:05
【问题描述】:


假设我们有一个字符串a = "01000111000011"n=5 "1"s。 ith "1",我想用"ORANGE" 中的ith 字符替换。 我的结果应该是这样的:

b = "0O000RAN0000GE"

在 Python 中解决这个问题的最好方法是什么?是否可以将索引绑定到每个替换?

非常感谢! 海尔加

【问题讨论】:

    标签: python string replace loops substitution


    【解决方案1】:

    大量的答案/方法来做到这一点。我的使用一个基本假设,即您的 #of 1 等于您要替换的单词的长度。

    a = "01000111000011"
    a = a.replace("1", "%s")
    b = "ORANGE"
    print a % tuple(b)
    

    或者 pythonic 1 衬垫 ;)

    print "01000111000011".replace("1", "%s") % tuple("ORANGE")
    

    【讨论】:

      【解决方案2】:
      a = '01000111000011'
      for char in 'ORANGE':
        a = a.replace('1', char, 1)
      

      或者:

      b = iter('ORANGE')
      a = ''.join(next(b) if i == '1' else i for i in '01000111000011')
      

      或者:

      import re
      a = re.sub('1', lambda x, b=iter('ORANGE'): b.next(), '01000111000011')
      

      【讨论】:

      • 这个答案的第一部分虽然很清楚,但性能却很糟糕。如果需要对多个字符串执行此任务,则不应使用它。
      • 如果原始字符串中的 1 多于替换字符中的 1,则此答案的第二部分将出现问题(尝试使用 '010001110000110101010101' 的解决方案)。
      【解决方案3】:
      s_iter = iter("ORANGE")
      "".join(next(s_iter) if c == "1" else c for c in "01000111000011")
      

      【讨论】:

      • 如果原始字符串中的 1 多于替换字符中的 1,则此答案将出现问题(尝试使用 '010001110000110101010101' 的解决方案)。
      【解决方案4】:

      如果源字符串中 1 的数量与替换字符串的长度不匹配,您可以使用以下解决方案:

      def helper(source, replacement):
          i = 0
          for c in source:
              if c == '1' and i < len(replacement):
                  yield replacement[i]
                  i += 1
              else:
                  yield c
      
      a = '010001110001101010101'
      b = 'ORANGE'
      a = ''.join(helper(a, b)) # => '0O000RAN000GE01010101'
      

      【讨论】:

        【解决方案5】:

        改进 bluepnume 的解决方案:

        >>> from itertools import chain, repeat
        >>> b = chain('ORANGE', repeat(None))
        >>> a = ''.join((next(b) or c) if c == '1' else c for c in '010001110000110101')
        >>> a
        '0O000RAN0000GE0101'
        

        [编辑]

        甚至更简单:

        >>> from itertools import chain, repeat
        >>> b = chain('ORANGE', repeat('1'))
        >>> a = ''.join(next(b) if c == '1' else c for c in '010001110000110101')
        >>> a
        '0O000RAN0000GE0101'
        

        [编辑] #2

        这也有效:

        import re
        >>> r = 'ORANGE'
        >>> s = '010001110000110101'
        >>> re.sub('1', lambda _,c=iter(r):next(c), s, len(r))
        '0O000RAN0000GE0101'
        

        【讨论】:

          猜你喜欢
          • 2016-07-20
          • 2021-08-19
          • 2020-01-10
          • 1970-01-01
          • 2021-06-18
          • 2021-06-26
          • 2018-09-08
          • 2018-03-24
          • 1970-01-01
          相关资源
          最近更新 更多