Explanation of how nested list comprehension works?

前端 未结 8 1238
情书的邮戳
情书的邮戳 2020-11-22 02:06

I have no problem for understanding this:

a = [1,2,3,4]
b = [x for x in a]

I thought that was all, but then I found this snippet:



        
相关标签:
8条回答
  • 2020-11-22 02:45

    Effectively:

    ...for xs in a...]
    

    is iterating over your main (outer) list and returning each of your sublists in turn.

    ...for x in xs]
    

    is then iterating over each of these sub lists.

    This can be re-written as:

    b = []
    for xs in a:
        for x in xs:
            b.append(x)
    
    0 讨论(0)
  • 2020-11-22 02:45

    It can be written like this

    result = []
    for xs in a:
        for x in xs:
            result.append(x)
    

    You can read more about it here

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