2

I'm trying to figure out how this list comprehension works, but I can't quite understand how it works. If somebody could write the non-list-comprehension equivalent I think I could understand.

This is the line I'm stuck on:

[item for sublist in li for item in sublist]

It's stated purpose is to flatted out multidimensional lists. Here's an example of me testing it:

>>> li = [[0,1],[1,3,5],[4,5,3,2]]
>>> [item for sublist in li for item in sublist]
[0, 1, 1, 3, 5, 4, 5, 3, 2]
4

2 回答 2

7

非列表理解等价物:

arr = []
for sublist in li:
    for item in sublist:
        arr.append( item )
于 2013-10-10T19:11:27.773 回答
2

等效的 for 循环版本如下所示:

result = []

for sublist in li:
    for item in sublist:
        result.append(item)

因此,for列表推导式中的语句顺序等同于它们在嵌套 for 语句中出现的顺序。

于 2013-10-10T19:11:39.067 回答