为什么循环嵌套的顺序很重要?

时间:2016-04-21 05:35:36

标签: python loops printing

我试图通读这本书:用python自动化无聊的东西。 我在第6章的练习项目:桌面打印机。 (https://automatetheboringstuff.com/chapter6/) - cmmd + F"桌面打印机"

我设法找到答案,但我发现我对嵌套循环的理解相当薄弱。为什么嵌套循环的顺序很重要?它如何影响打印数据的方式?

这是数据:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
         ['Alice', 'Bob', 'Carol', 'David'],
         ['dogs', 'cats', 'moose', 'goose']]

这是第一个代码:

for a in range(len(tableData[0])):
    for b in range(len(tableData)):
        print(tableData[b][a],end = "")
    print()

它打印出来:

  apples   Alice    dogs
 oranges     Bob    cats
cherries   Carol   moose
  banana   David   goose

这是第二个代码 (我改变了a和b的顺序嵌套,没有改变我想要打印的内容):

for b in range(len(tableData)):
    for a in range(len(tableData[0])):
        print(tableData[b][a],end = "")
    print()

它打印出来:

apples orangescherries  banana
   Alice     Bob   Carol   David
    dogs    cats   moose   goose

这是第3段代码(我没有改变嵌套的顺序,但改变了我想要打印的内容):

for a in range(len(tableData[0])):
    for b in range(len(tableData)):
        print(tableData[a][b],end = "")
    print()

打印出来:

  apples orangescherries
   Alice     Bob   Carol
    dogs    cats   moose
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    printTable()
  File "<pyshell#11>", line 10, in printTable
    print(tableData[x][j].rjust(colWidths[0]),end = "")
IndexError: list index out of range

我理解困难的是:

(1)对于第一个和第二个代码 - 为什么嵌套的顺序会影响打印的内容?

(2)对于第1和第3代码 - 为什么打印[a] [b]的顺序很重要?

对不起,这是一个非常长的问题,但我遇到了一些麻烦,请帮帮我。

2 个答案:

答案 0 :(得分:4)

您在Python中创建的表格list包含list s。

table = [ ["row 0, column 0", "row 0, column 1", "row 0, column 2"],
          ["row 1, column 0", "row 1, column 1", "row 1, column 2"],
          ["row 2, column 0", "row 2, column 1", "row 2, column 2"],
          ["row 3, column 0", "row 3, column 1", "row 3, column 2"] ]

这就是你如何从这样一个&#34;多维&#34;列表:

row = table[1]  # get row 1 (2nd item of the outer list)
item = row[3]  # from row 1, get column 3 (4th item of the inner list)

或简而言之:

item = table[1][3]  # get item 1 of the outer list, and from that inner list get item 3

这就解释了为什么从&#34;多维&#34;访问项目时的参数顺序。列出事项,第一个索引选择行,第二个索引选择列(如果我们想象列表列表如上所示)。

现在嵌套循环:

for row_number in range(len(table)):  # iterate over the row indices

    for column_number in range(len(table[row_number])):  # iterate over the column indices 
                                                         # of the current row

        print("Row:", row_number, "- Column:", column_number)
        print(" --> Item:", table[row_number][column_number])

        # <-- jump back to the column loop head here, if elements remaining

    # <-- jump back to the row loop head here, if elements remaining

因此外循环(行)计数较慢而内循环(列)计数较快,因为对于外循环的每个迭代步骤,内循环对其所有元素执行完整迭代。

但是,您不应该迭代Python中的列表索引,但是您可以直接遍历列表项。它也变得更加清晰:

for row in table:  # iterate over the rows (items of the outer list)

    for column in row:  # iterate over the columns of the current row (items of inner list)

        print("Row:", row_number, "- Column:", column_number)
        print(" --> Item:", table[row_number][column_number])

        # <-- jump back to the column loop head here, if elements remaining

    # <-- jump back to the row loop head here, if elements remaining

答案 1 :(得分:2)

我做了一个可能对你有帮助的MSPaint插图和类比。

如果您认为您的数据生活在矩形网格中,就像城市一样,它可能有所帮助。想象一下,你有一个宽4个街区(从西到东)和3个街区(从北向南)的城市。你想访问每个街区。

您来访时主要是从北向南旅行吗?你必须从第一个街区开始然后向南走3个街区,然后向东移动一个街区并从北面开始。这样做4次。这称为“列主要订单”。

您的访问大多是从西向东旅行吗?你必须从第一个街区开始然后向东走4个街区,然后向南移动一个街区并从西边开始。这样做3次。这被称为“行主要订单”。

如您所见,您可以按照不同的顺序访问块,具体取决于您的访问路径是行主要还是列主要。按照箭头将其顺序与数据输出的顺序相匹配。

在最后一种情况下,你仍然按行主要顺序访问,但是你只想向东走3个街区,向南走4个街区。你已经混淆了你所在城市的规模,你可能最终会进入贫民窟(在第三张照片中用一些问号表示)。

编辑:图片顺序错误。我的话都混淆了。我认为现在已经修好了。

Row vs column major ordering