How do I merge a 2D array in Python into one string with List Comprehension?

后端 未结 8 716
囚心锁ツ
囚心锁ツ 2020-12-29 07:49

List Comprehension for me seems to be like the opaque block of granite that regular expressions are for me. I need pointers.

Say, I have a 2D list:

l         


        
8条回答
  •  粉色の甜心
    2020-12-29 07:55

    There's a couple choices. First, you can just create a new list and add the contents of each list to it:

    li2 = []
    for sublist in li:
        li2.extend(sublist)
    

    Alternately, you can use the itertools module's chain function, which produces an iterable containing all the items in multiple iterables:

    import itertools
    li2 = list(itertools.chain(*li))
    

    If you take this approach, you can produce the string without creating an intermediate list:

    s = ",".join(itertools.chain(*li))
    

提交回复
热议问题