How to join every sublist to a single string in Python?
Here is the list :
L=[['1', '1', '0', '0', '0'],['1', '1', '1', '1', '0'],['0', '0', '1', '1', '0']]
My desired list would be :
D=['11000','11110','00110']
How to join every sublist to a single string in Python?
Here is the list :
L=[['1', '1', '0', '0', '0'],['1', '1', '1', '1', '0'],['0', '0', '1', '1', '0']]
My desired list would be :
D=['11000','11110','00110']
L = [['1', '1', '0', '0', '0'],['1', '1', '1', '1', '0'],['0', '0', '1', '1', '0']]
D = [''.join(sub_list) for sub_list in L]
You can either use a list comprehension:
L = [
['1', '1', '0', '0', '0'],
['1', '1', '1', '1', '0'],
['0', '0', '1', '1', '0']
]
D = [''.join(l) for l in L]
or the map function:
D = map(''.join, L) # returns a generator in python3, cast it to list to get one
Note that the most pythonic way of doing this is the list comprehension.
reduce
easily.All you need to use initializer - third argument in the reduce
function.
reduce(
lambda result, _list: result.append(''.join(_list)) or result,
L,
[])
import operator
map(lambda l: reduce(operator.iconcat, l), L)
Above code works for both python2 and python3, but you need to import reduce module as from functools import reduce
. Refer below link for details.