将多个列表推导组合到列表列表中

时间:2018-03-15 15:18:24

标签: python numpy list-comprehension sudoku

我知道我的标题也有类似的问题,但我找不到与下面概述的问题类似的问题:

我试图将以下9个列表推导存储到一个列表中,以便每个列表推导本身都是新列表中的列表:

a = [(i,j) for i in range(3) for j in range(3)]
b = [(i,j) for i in range(3) for j in range(3,6)]
c = [(i,j) for i in range(3) for j in range(6,9)]

d = [(i,j) for i in range(3,6) for j in range(3)]
e = [(i,j) for i in range(3,6) for j in range(3,6)]
f = [(i,j) for i in range(3,6) for j in range(6,9)]

g = [(i,j) for i in range(6,9) for j in range(3)]
h = [(i,j) for i in range(6,9) for j in range(3,6)]
i = [(i,j) for i in range(6,9) for j in range(3,9)]

具体来说,这些打印出了数独板中BLOCKS的索引。我想将每个块作为一个列表中的列表。

是否有人能够指出我正确的方向。

由于

3 个答案:

答案 0 :(得分:2)

我可以想到两种方式,对你所拥有的东西进行微不足道的重写:

1)master_list = [a,b,c,d,e,f,g,h,i]也就是说,只需获取您已获得的单独命名列表并将其放入列表中。

2)

master_list = [
    [(i,j) for i in range(3) for j in range(3)],
    [(i,j) for i in range(3) for j in range(3,6)],
    [(i,j) for i in range(3) for j in range(6,9)],

    [(i,j) for i in range(3,6) for j in range(3)],
    [(i,j) for i in range(3,6) for j in range(3,6)],
    [(i,j) for i in range(3,6) for j in range(6,9)],

    [(i,j) for i in range(6,9) for j in range(3)],
    [(i,j) for i in range(6,9) for j in range(3,6)],
    [(i,j) for i in range(6,9) for j in range(3,9)],
]

这基本相同,但没有中间变量名。

答案 1 :(得分:0)

合理化一点,你可以定义一个函数

def f(b, r):
    return [(i, j) for i in range(b, b+3) for j in range(*r)]

并用想要的范围驱动它

ml = [f(b, r) for b in range(0, 9, 3) for r in ((0, 3), (3, 6), (6, 9))]

答案 2 :(得分:0)

不确定你的最后一行是否正确,相当确定它应该是

[(i,j) for i in range(6,9) for j in range(6,9)]

不是

[(i,j) for i in range(6,9) for j in range(3,9)]

因为这是3x6网格。

尽管如此,这是一个更清晰的列表组件,用于创建9个3x3网格:

[[(x0*3 + i, y0*3 + j) for x in range(3) for y in range(3)] for x0 in range(3) for y0 in range(3)]