Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 404
Shijith Avatar asked Jun 06 '19 14:06

Shijith


People also ask

How do I concatenate a list of strings?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.

How do you concatenate two lists of strings in Python?

Python's extend() method can be used to concatenate two lists in Python. The extend() function does iterate over the passed parameter and adds the item to the list thus, extending the list in a linear fashion. All the elements of the list2 get appended to list1 and thus the list1 gets updated and results as output.

How do I merge nested lists in Python?

Method 1: Using nested for loop Create a variable to store the input list of lists(nested list). Use the append() function(adds the element to the list at the end) to add this element to the result list. Printing the resultant list after joining the input list of lists.


2 Answers

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.

like image 125
yatu Avatar answered Sep 16 '22 22:09

yatu


Not as elegant as yatu's answer but if you're using pandas:

import pandas as pd
pd.DataFrame(lst).sum(axis=0)

# 0    a@1
# 1    b$2
# 2    c#3
# dtype: object

Pandas Series have a .tolist() method to get the expected output:

series = pd.DataFrame(lst).sum(axis=0)
series.tolist()

# ['a@1', 'b$2', 'c#3']
like image 38
ajrwhite Avatar answered Sep 17 '22 22:09

ajrwhite