【问题标题】:How to concatenate element-wise two lists in Python如何在 Python 中按元素连接两个列表
【发布时间】:2013-11-02 19:30:32
【问题描述】:

我有两个列表,我想按元素连接它们。列表之一在连接之前经过字符串格式化。

例如:

a = [0, 1, 5, 6, 10, 11] 
b = ['asp1', 'asp1', 'asp1', 'asp1', 'asp2', 'asp2']

在这种情况下,a 会进行字符串格式化。也就是说,新的a 或aa 应该是:

aa = [00, 01, 05, 06, 10, 11]

最终输出应该是:

c = ['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211']

有人可以告诉我怎么做吗?

【问题讨论】:

  • 试试zip和string.format
  • @FrancescoMontesano 谢谢,nightcracker 的回答工作正常!
  • @nightcracker 感谢您的回答。是的,当然。但是,我不能接受你刚才的回答。显示等待 5 分钟。然后,我会这样做:)

标签: python list


【解决方案1】:

使用zip:

>>> ["{}{:02}".format(b_, a_) for a_, b_ in zip(a, b)]
['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211']

【讨论】:

  • @dmedvinsky 这个呢? c = map("{0[1]}{0[0]:02}".format, zip(a, b)) 让魔法开始吧!
  • @nightcracker:很好。 map 的示例适用于 python2。对于python3,如果你想要一个列表,你需要list(map(...)),而列表理解对两者都有效
  • 你不需要需要,如果你需要一个列表,你只需要它(即一个可迭代是不够的)。
【解决方案2】:

使用压缩包

[m+str(n) for m,n in zip(b,a)]

输出

['asp10', 'asp11', 'asp15', 'asp16', 'asp210', 'asp211']

【讨论】:

    【解决方案3】:

    其他解决方案(更喜欢 printf 格式化 样式而不是 .format() 用法),它也更小:

    >>> ["%s%02d" % t for t in zip(b, a)]
    ['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211']
    

    【讨论】:

      【解决方案4】:

      这可以用 map 和 zip 优雅地完成:

      map(lambda (x,y): x+y, zip(list1, list2))
      

      例子:

      In [1]: map(lambda (x,y): x+y, zip([1,2,3,4],[4,5,6,7]))
      Out[1]: [5, 7, 9, 11]
      

      【讨论】:

      • 它没有按照 OP 的要求进行操作
      • 不,但这是一般模式,我认为这更重要。
      • @EdgarKlerks,我收到了SyntaxError: invalid syntax 这个代码示例......
      【解决方案5】:

      输入:

      a = [0, 1, 5, 6, 10, 11] 
      b = ['asp1', 'asp1', 'asp1', 'asp1', 'asp2', 'asp2']
      
      concat_func = lambda x,y: x + "" + str(y)
      
      list(map(concat_func,b,a)) # list the map function
      

      输出:

      ['asp10', 'asp11', 'asp15', 'asp16', 'asp210', 'asp211']
      

      【讨论】:

      • 对于不同长度的列表可以这样做吗?
      【解决方案6】:

      如果你想连接任意数量的列表,你可以这样做:

      In [1]: lists = [["a", "b", "c"], ["m", "n", "o"], ["p", "q", "r"]] # Or more
      
      In [2]: lists
      Out[2]: [['a', 'b', 'c'], ['m', 'n', 'o'], ['p', 'q', 'r']]    
      
      In [4]: list(map("".join, zip(*lists)))
      Out[4]: ['amp', 'bnq', 'cor']
      

      【讨论】:

      • 我认为,这个答案应该得到更多的信任。如果一个有可变数量的列表。假设在数据准备中你有正面和负面(用户可以定义负面的数量),那么上面的解决方案将通过可变数量的负面列表来解决这个问题。
      【解决方案7】:

      不使用 zip。我不知道,我认为这是显而易见的方法。也许我刚学了 C :)

      c=[]
      for i in xrange(len(a)):
          c.append("%s%02d" % (b[i],a[i]))
      

      【讨论】:

        【解决方案8】:
        b = ['asp1', 'asp1', 'asp1', 'asp1', 'asp2', 'asp2']
        aa = [0, 1, 5, 6, 10, 11]
        new_list =[]
        if len(aa) != len(b):
             print 'list length mismatch'
        else:
            for each in range(0,len(aa)):
                new_list.append(b[each] + str(aa[each]))
        print new_list
        

        【讨论】:

          【解决方案9】:

          我最终使用了一个临时 DataFrame,它可读且快速:

          a = ["a", "b", "c"]
          b = ["1", "2", "3"]
          
          df = pd.DataFrame({"a": a, "b": b})
          df["c"] = df.a + df.b
          result = df.c.values
          

          输出:

          $ result 
          ["a1", "b2", "c3"]
          

          在幕后,DataFrames 使用 numpy,所以结果是高效的。


          和函数一样的东西:

          import pandas as pd
          from typing import List
          def _elementwise_concat(self, a: List[str], b: List[str]) -> List[str]:
              """
              Elementwise concatenate.
              :param a: List of strings.
              :param b: List of strings.
              :return: List, same length, strings concatenated.
              """
              df = pd.DataFrame({"a": a, "b": b})
              df["c"] = df.a + df.b
              return df.c.values
          

          【讨论】:

            【解决方案10】:

            列表理解/zip()/使用zfill() 格式化。

            print ([y+str(x).zfill(2) for x,y in zip(a,b)])
            

            输出:

            ['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211']
            

            【讨论】:

              【解决方案11】:

              使用lambda 和format:

              b = ['asp1', 'asp1', 'asp1', 'asp1', 'asp2', 'asp2']
              a = [0, 1, 5, 6, 10, 11]
              
              list(map(lambda x: x[0] + "{0:0=2d}".format(x[1]), zip(b, a)))
              

              输出:

              ['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211']
              

              【讨论】:

                猜你喜欢
                • 2022-06-17
                • 2022-12-03
                • 2020-05-08
                • 2010-12-15
                • 1970-01-01
                • 2019-09-02
                相关资源
                最近更新 更多