Element wise concatenate multiple lists (list of list of strings)

前端 未结 3 782
独厮守ぢ
独厮守ぢ 2020-12-20 18:54

i have a list of list of strings as below

lst = [[\'a\',\'b\',\'c\'],[\'@\',\'$\',\'#\'],[\'1\',\'2\',\'3\']]

I want to concatenate each

3条回答
  •  醉话见心
    2020-12-20 19:19

    Here's one way zipping the sublists and mapping with ''.join the resulting tuples:

    list(map(''.join, zip(*lst)))
    # ['a@1', 'b$2', 'c#3']
    

    Here zip as shown in the docs aggregates elements from several iterables. With *, we are unpacking the list into separate iterables, which means that the function will instead be receiving zip(['a','b','c'],['@','$','#'],['1','2','3']).

    Now at each iteration, map will be applying ''.join to each of the aggregated iterables, i.e to the first element in each sublist, then the second, and so on.

提交回复
热议问题