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

前端 未结 3 854
自闭症患者
自闭症患者 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

提交回复
热议问题