Python – Understand and extend using lists

Understand and extend using lists… here is a solution to the problem.

Understand and extend using lists

I have this

rows = self.rows()
aaa = []
for r in range(0, 9, 3):
    bbb = []
    for c in range(0, 9, 3):
        ccc = []
        for s in range(3):
            ccc.extend(rows[r+s][c:c+3])
        bbb.append(ccc)
    aaa.append(bbb)

It returns this

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

That’s right.
rows Just a list of 9 other nested lists, each with exactly 9 integers, ranging from 0 to 9.

When I try to use list understanding

[[rows[r+s][c:c+3] for s in range(3) for c in range(0, 9, 3)] for r in range(0, 9, 3)]

I understand

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

Apparently I did something wrong, but what can’t I see? I checked other SO issues and they hinted at somehow structuring the LC to prevent the innermost list from splitting into 9 separate lists, but so far it hasn’t happened.

Solution

Try:

import itertools

[[list(itertools.chain(*[rows[r+s][c:c+3] for s in range(3)])) for c in range(0, 9, 3)] for r in range(0, 9, 3)]

Related Problems and Solutions