【问题标题】:Simplifying a few rows of code using a for loop?使用 for 循环简化几行代码?
【发布时间】:2018-07-12 17:55:47
【问题描述】:

在尝试制作数独解谜程序时,我遇到了一个小问题。也就是说,我想追加到列表中的行(列表)的数量。

# 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 循环或类似的帮助下附加所有这些列表?

【问题讨论】:

标签: python python-3.x


【解决方案1】:

您可以使用一个称为“网格”的二维数组,而不是使用九个行变量。

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]]

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

【讨论】:

  • @scharette 如果是java什么的,他需要在整个事情的末尾加一个分号。
  • @Forsarna_ Alex 发布的代码是有效的 javascript 代码,因为 var
【解决方案2】:

这可能是间接解决方案。考虑使用二维列表或矩阵。对于二维列表,请参阅其他答案;有关矩阵,请参阅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 矩阵的一个好处是输入和输出是“美化的”,并且可以访问额外的 numpy 方法和属性,这些方法和属性在实现数独游戏时非常有用。

【讨论】:

    【解决方案3】:

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

    # 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 = []
    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
    

    【讨论】:

    • 您不需要使用 append 来避免超出范围的错误吗?
    • @BenJones 你是完全正确的让我编辑我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 2011-10-12
    相关资源
    最近更新 更多