python list comprehension double for

后端 未结 4 1138
终归单人心
终归单人心 2020-12-02 05:35
vec = [[1,2,3], [4,5,6], [7,8,9]]
print [num for elem in vec for num in elem]      <----- this

>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]

This is

4条回答
  •  失恋的感觉
    2020-12-02 06:15

    From the list comprehension documentation:

    When a list comprehension is supplied, it consists of a single expression followed by at least one for clause and zero or more for or if clauses. In this case, the elements of the new list are those that would be produced by considering each of the for or if clauses a block, nesting from left to right, and evaluating the expression to produce a list element each time the innermost block is reached.

    In other words, pretend that the for loops are nested. Reading from left to right your list comprehension can be nested as:

    for elem in vec:
        for num in elem:
            num           # the *single expression* from the spec
    

    where the list comprehension will use that last, innermost block as the values of the resulting list.

提交回复
热议问题