使用for循环简化几行代码?

时间:2018-07-12 17:55:47

标签: python python-3.x

在尝试创建数独解决程序时,我遇到了一个小问题。也就是说,我要追加到列表中的行数(列表)。

# These are the lists that i have to append

row0 = [5,3,0, 0,7,0, 0,0,0]
row1 = [6,0,0, 1,9,5, 0,0,0]
row2 = [0,9,8, 0,0,0, 0,6,0]

row3 = [8,0,0, 0,6,0, 0,0,3]
row4 = [4,0,0, 8,0,3, 0,0,1]
row5 = [7,0,0, 0,2,0, 0,0,6]

row6 = [0,6,0, 0,0,0, 2,8,0]
row7 = [0,0,0, 4,1,9, 0,0,5]
row8 = [0,0,0, 0,8,0, 0,7,9]


# And this, is what i want to avoid doing.

rows.append(row0)
rows.append(row1)
rows.append(row2)

rows.append(row3)
rows.append(row4)
rows.append(row5)

rows.append(row6)
rows.append(row7)
rows.append(row8)

是否可以在for循环或类似的帮助下附加所有这些列表?

3 个答案:

答案 0 :(得分:4)

您可以使用一个称为“网格”的2D数组来代替使用9个行变量。

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

这样,可以在一行中复制网格。

答案 1 :(得分:0)

为什么不将原始列表放在自己的列表中,以便您可以遍历它们?

# These are the lists that i have to append
rowsToAppend = []
rowsToAppend.append([5,3,0, 0,7,0, 0,0,0])
rowsToAppend.append([6,0,0, 1,9,5, 0,0,0])
# etc...


for row in rowsToAppend:
    rows.append(row)

或者当然,您可以立即定义行数组

rows = []
rows.append([5,3,0, 0,7,0, 0,0,0])
rows.append([6,0,0, 1,9,5, 0,0,0])
# etc...
# No need to append since it's already done

答案 2 :(得分:0)

这可能是间接解决方案。考虑使用二维列表或矩阵。对于二维列表,请参见其他答案。有关矩阵,请参见numpy.matrix

从本质上讲,您将具有以下内容:

>>> a = np.matrix('1 2; 3 4')
>>>print(a)
[[1 2]
 [3 4]]

>>> np.matrix([[1, 2], [3, 4]])
matrix([[1, 2],
        [3, 4]])

使用numpy矩阵的好处之一是“美化”了输入和输出,并且可以访问在实现suduku游戏中非常有用的其他numpy方法和属性。