【问题标题】:How to merge two lists of string in Python如何在Python中合并两个字符串列表
【发布时间】:2015-09-01 19:25:32
【问题描述】:

我有两个字符串列表:

a = ['a', 'b', 'c']
b = ['d', 'e', 'f']

我应该结果:

['ad', 'be', 'cf']

最pythonic的方法是什么?

【问题讨论】:

    标签: python string list merge


    【解决方案1】:

    可能是zip:

    c = [''.join(item) for item in zip(a,b)]
    

    您还可以将多个子列表放入一个大的可迭代对象中,并使用* 运算符对其进行解包,将每个子列表作为单独的参数传递给zip:

    big_list = (a,b)
    c = [''.join(item) for item in zip(*biglist)]
    

    您甚至可以将* 运算符与zip 一起使用以朝另一个方向发展:

    >>> list(zip(*c))
    [('a', 'b', 'c'), ('d', 'e', 'f')]
    

    【讨论】:

    • 这个也适用于任意数量的列表,使用zip(*list_of_lists)。
    • 是的。另外请记住,您可以使用* 运算符来取消zip 事物:list(zip(*c)) 产生[('a', 'b', 'c'), ('d', 'e', 'f')]。
    【解决方案2】:

    您可以使用zip

    >>> a = ['a', 'b', 'c']
    >>> b = ['d', 'e', 'f']
    
    >>> [ai+bi for ai,bi in zip(a,b)]
    
    ['ad', 'be', 'cf']
    

    【讨论】:

      【解决方案3】:

      怎么样:

      [c + d for c,d in zip(a,b)]
      

      【讨论】:

        【解决方案4】:

        你可以使用zip:

        zip(a,b)
        [('a', 'd'), ('b', 'e'), ('c', 'f')]
        
        [x+y for x,y in zip(a,b)]
        ['ad', 'be', 'cf']
        

        您还可以将 enumerate 与列表理解一起使用:

        [j+b[i] for i,j in enumerate(a)]
        ['ad', 'be', 'cf']
        

        【讨论】:

          【解决方案5】:

          您可以将lambda 与map 一起使用:

          map(lambda x,y:x+y,a,b)
          

          或者添加zip来管理2个以上的列表:

          map(lambda x:''.join(x), zip(a,b,c))
          

          对于 python zip() 替换为 izip(),对于 python 3,不需要更改(zip 已经返回一个迭代器)。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-09-11
            • 1970-01-01
            • 1970-01-01
            • 2017-07-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多