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

后端 未结 8 713
囚心锁ツ
囚心锁ツ 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 08:13

    Like so:

    [ item for innerlist in outerlist for item in innerlist ]
    

    Turning that directly into a string with separators:

    ','.join(str(item) for innerlist in outerlist for item in innerlist)
    

    Yes, the order of 'for innerlist in outerlist' and 'for item in innerlist' is correct. Even though the "body" of the loop is at the start of the listcomp, the order of nested loops (and 'if' clauses) is still the same as when you would write the loop out:

    for innerlist in outerlist:
        for item in innerlist:
            ...
    

提交回复
热议问题