How to join every sublist to a single string in Python?

前端 未结 3 838
自闭症患者
自闭症患者 2020-12-07 05:55

MWE: Here is the list :

L=[[\'1\', \'1\', \'0\', \'0\', \'0\'],[\'1\', \'1\', \'1\', \'1\', \'0\'],[\'0\', \'0\', \'1\', \'1\', \'0\']]
<         


        
相关标签:
3条回答
  • 2020-12-07 05:57

    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.

    • for python2

    • for python3

    0 讨论(0)
  • 2020-12-07 06:05

    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.

    0 讨论(0)
  • 2020-12-07 06:17
    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]
    
    0 讨论(0)
提交回复
热议问题