【问题标题】:Add two different values to string from different lists将两个不同的值添加到来自不同列表的字符串
【发布时间】:2013-07-12 21:12:44
【问题描述】:

所以我有两个不同的字符串列表;即 x 和 y。

len(y) = len(x) - 1

我想以原始顺序将它们添加到一个空字符串中,所以基本上输出 = x1 + y1 + x2 + y2 + x3

x = ['AAA','BBB','CCC']
y = ['abab','bcbcb']

#z = ''
z = 'AAAababBBBbcbcbCCC'

如何创建一个 for 循环来添加到这个空字符串 z ?

我通常会这样做:

for p,q in zip(x,y):

但由于y小于x,它不会添加x的最后一个值

【问题讨论】:

    标签: python string list add


    【解决方案1】:

    应该这样做:

    ''.join([item for sublist in zip(x, y+['']) for item in sublist])
    

    【讨论】:

      【解决方案2】:

      你想要itertools.izip_longest。另外,请查看this other post

      newStr = ''.join(itertools.chain.from_iterable(
                         itertools.izip_longest(x,y, fillvalue='')
                       ))
      

      【讨论】:

      • 更多行!这对于单行来说太长了。
      【解决方案3】:

      您可以使用来自 itertools 的 roundrobin recipe

      from itertools import *
      def roundrobin(*iterables):
          "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
          # Recipe credited to George Sakkis
          pending = len(iterables)
          nexts = cycle(iter(it).next for it in iterables)
          while pending:
              try:
                  for next in nexts:
                      yield next()
              except StopIteration:
                  pending -= 1
                  nexts = cycle(islice(nexts, pending))
      x = ['AAA','BBB','CCC']
      y = ['abab','bcbcb']
      print "".join(roundrobin(x,y))  
      #AAAababBBBbcbcbCCC          
      

      或者使用itertools.izip_longest 你可以这样做:

      >>> from itertools import izip_longest
      >>> ''.join([''.join(c) for c in izip_longest(x,y,fillvalue = '')])
      'AAAababBBBbcbcbCCC'
      

      【讨论】:

        【解决方案4】:
        from itertools import izip_longest
        
        x = ['AAA','BBB','CCC']
        y = ['abab','bcbcb']
        
        unfinished_z = izip_longest( x,y,fillvalue='' ) # an iterator
        unfinished_z = [ ''.join( text ) for text in unfinished_z ] # a list
        z = ''.join( unfinished_z ) # the string AAAababBBBbcbcbCCC
        

        我更喜欢冗长。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-10-13
          • 2020-04-28
          • 2021-12-14
          • 2022-01-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-08
          相关资源
          最近更新 更多