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.
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.
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.
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.
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With