Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
547 views
in Technique[技术] by (71.8m points)

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

i have a list of list of strings as below

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

I want to concatenate each string inside the lists element wise, expected output as below:

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

The size of lst can vary. is there any way to accomplish this without going through for loops.
I tried to use map, but its not working.

map(str.__add__,(x for x in list))

please help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...