How does the list comprehension to flatten a python list work?

后端 未结 5 1417
忘了有多久
忘了有多久 2020-12-30 06:50

I recently looked for a way to flatten a nested python list, like this: [[1,2,3],[4,5,6]], into this: [1,2,3,4,5,6].

Stackoverflow was helpful as ever and I found a

5条回答
  •  时光说笑
    2020-12-30 07:46

    The for loops are evaluated from left to right. Any list comprehension can be re-written as a for loop, as follows:

    l = [[1,2,3],[4,5,6]]
    flattened_l = []
    for sublist in l:
        for item in sublist:
            flattened_l.append(item)
    

    The above is the correct code for flattening a list, whether you choose to write it concisely as a list comprehension, or in this extended version.

    The second list comprehension you wrote will raise a NameError, as 'sublist' has not yet been defined. You can see this by writing the list comprehension as a for loop:

    l = [[1,2,3],[4,5,6]]
    flattened_l = []
    for item in sublist:
        for sublist in l:
            flattened_l.append(item)
    

    The only reason you didn't see the error when you ran your code was because you had previously defined sublist when implementing your first list comprehension.

    For more information, you may want to check out Guido's tutorial on list comprehensions.

提交回复
热议问题