2

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'] 
philipxy
  • 14,867
  • 6
  • 39
  • 83
Primo
  • 413
  • 1
  • 6
  • 7

3 Answers3

5
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]
user3483203
  • 50,081
  • 9
  • 65
  • 94
abigperson
  • 5,252
  • 3
  • 22
  • 25
2

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.

Adrien El Zein
  • 179
  • 2
  • 6
0

flat list can be made through 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, 
   [])

or map and reduce in combination,

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.