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

后端 未结 8 687
囚心锁ツ
囚心锁ツ 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:
            ...
    
    0 讨论(0)
  • 2020-12-29 08:16

    To make it a flattened list use either:

    1. http://code.activestate.com/recipes/121294/
    2. http://code.activestate.com/recipes/363051/

    Then, join to make it a string.

    0 讨论(0)
提交回复
热议问题