【问题标题】:Replace one item in a string with one item from a list用列表中的一项替换字符串中的一项
【发布时间】:2017-04-26 01:43:25
【问题描述】:

我有一个字符串和一个列表:

seq = '01202112'

l = [(0,1,0),(1,1,0)]

我想要一种 Python 方式,将每个 '2' 替换为列表 l 中相应索引处的值,以便我获得两个新字符串:

list_seq = [01001110, 01101110]

通过使用.replace(),我可以遍历l,但我想知道是否有更pythonic 的方式来获取list_seq

【问题讨论】:

    标签: python python-2.7 list replace sequence


    【解决方案1】:
    [''.join([str(next(digit, 0)) if x is '2' else x for x in seq])
     for digit in map(iter, l)]
    

    【讨论】:

      【解决方案2】:
      seq = '01202112'
      li = [(0,1,0),(1,1,0)]
      
      def grunch(s, tu):
          it = map(str,tu)
          return ''.join(next(it) if c=='2' else c for c in s)
      
      list_seq = [grunch(seq,tu) for tu in li]
      

      【讨论】:

        【解决方案3】:

        我可能会这样做:

        out = [''.join(c if c != '2' else str(next(f, c)) for c in seq) for f in map(iter, l)]
        

        基本思想是我们调用iterl 中的元组变成迭代器。那时,每次我们对它们调用 next 时,我们都会得到下一个需要使用的元素,而不是 '2'

        如果这太紧凑,逻辑可能更容易作为函数阅读:

        def replace(seq, to_replace, fill):
            fill = iter(fill)
            for element in seq:
                if element != to_replace:
                    yield element
                else:
                    yield next(fill, element)
        

        给予

        In [32]: list(replace([1,2,3,2,2,3,1,2,4,2], to_replace=2, fill="apple"))
        Out[32]: [1, 'a', 3, 'p', 'p', 3, 1, 'l', 4, 'e']
        

        感谢 cmets 中的 @DanD 指出我一直认为我总是有足够的字符来填充!如果我们用完了,我们将按照他的建议保留原始字符,但是修改这种方法以使其表现不同是很简单的,并留给读者作为练习。 :-)

        【讨论】:

        • 如果输出用完了,这将截断输出。保持不变需要yield next(fill, element)
        【解决方案4】:

        我不知道这个解决方案是否“更 Pythonic”,但是:

        def my_replace(s, c=None, *other):
                return s if c is None else my_replace(s.replace('2', str(c), 1), *other)
        
        
        seq = '01202112'
        l = [(0,1,0),(1,1,0)]
        
        list_req = [my_replace(seq, *x) for x in l] 
        

        【讨论】:

          猜你喜欢
          • 2021-03-27
          • 1970-01-01
          • 2014-04-14
          • 1970-01-01
          • 2012-08-18
          • 2020-02-22
          • 2015-08-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多