Idiom for flattening a shallow nested list: how does it work?

前端 未结 4 960
闹比i
闹比i 2021-01-05 10:57

I found this bit of code in a module I am working on:

l = opaque_function()
thingys = [x for y in l for x in y]

I can\'t read this. By expe

4条回答
  •  礼貌的吻别
    2021-01-05 11:54

    From the list displays 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.

    Thus, your expression can be rewritten as:

    thingys = []
    for y in l:
        for x in y:
            thingys.append(x)
    

提交回复
热议问题