How to concatenate element-wise two lists in Python?

后端 未结 8 2492
春和景丽
春和景丽 2020-11-29 02:24

I have two lists and I want to concatenate them element-wise. One of the list is subjected to string-formatting before concatenation.

For example :

         


        
相关标签:
8条回答
  • 2020-11-29 02:44

    Than can be done elegantly with map and zip:

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

    Example:

    In [1]: map(lambda (x,y): x+y, zip([1,2,3,4],[4,5,6,7]))
    Out[1]: [5, 7, 9, 11]
    
    0 讨论(0)
  • 2020-11-29 02:44

    inputs:

    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
    

    output:

    ['asp10', 'asp11', 'asp15', 'asp16', 'asp210', 'asp211']
    
    0 讨论(0)
  • 2020-11-29 02:44

    If you wanted to concatenate arbitrary number of lists, you could do this:

    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']
    
    0 讨论(0)
  • 2020-11-29 02:47

    Use zip:

    >>> ["{}{:02}".format(b_, a_) for a_, b_ in zip(a, b)]
    ['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211']
    
    0 讨论(0)
  • 2020-11-29 02:52

    not using zip. I dunno, I think this is the obvious way to do it. Maybe I just learnt C first :)

    c=[]
    for i in xrange(len(a)):
        c.append("%s%02d" % (b[i],a[i]))
    
    0 讨论(0)
  • 2020-11-29 02:56

    Other solution (preferring printf formating style over .format() usage), it's also smaller:

    >>> ["%s%02d" % t for t in zip(b, a)]
    ['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211']
    
    0 讨论(0)
提交回复
热议问题