How to read aloud Python List Comprehensions?

后端 未结 2 1195
无人共我
无人共我 2020-11-30 04:08

My question is about Python List Comprehension readability. When I come across code with complex/nested list comprehensions, I find that I have to re-read t

相关标签:
2条回答
  • 2020-11-30 04:41

    "Construct a list of X's based on Y's and Z's for which Q is true."

    0 讨论(0)
  • 2020-11-30 04:50

    I usually unfold it in my mind into a generating loop, so for example

    [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
    

    is the list comprehension for the generator

    for x in [1,2,3]:
        for y in [3,1,4]:
            if x != y:
                yield (x, y)
    

    Example #1

    [x for b in a for x in b] is the comprehension for

    for b in a:
        for x in b:
            yield x
    

    Example result for a = [[1,2,3],[4,5,6]]: [1, 2, 3, 4, 5, 6]


    Example #2

    [[row[i] for row in matrix] for i in range(4)] (note the inner expression is another comprehension!):

    for i in range(4):
        yield [row[i] for row in matrix]
    

    which is unfolded

    for i in range(4):
        l = []
    
        for row in matrix:
            l.append(row[i])
    
        yield l
    
    0 讨论(0)
提交回复
热议问题