python中的for循环流

时间:2019-02-13 19:01:58

标签: python for-loop multidimensional-array

我只是python的新手,我为从用户获取数组值编写代码,因此我昨天在stackoverflow中问了一个问题。 Darius Morawiec和Austin给了我最好的称呼,但我不了解for循环的流程,我用google搜索,但我不理解这些解释。任何机构都可以为下面的给定代码解释“ for”循环的控制。谢谢

arr = [[int(input("Enter value for {}. row and {}. column: ".format(r + 1, c + 1))) 
       for c in range(n_cols)] 
       for r in range(n_rows)]

yesterday conversation Link

2 个答案:

答案 0 :(得分:0)

尽管共享相同的关键字,但这不是for循环;这是嵌套在另一个列表理解中的列表理解。因此,您需要先评估内部列表:

[
  [int(input("Enter value for {}. row and {}. column: ".format(r + 1, c + 1))) 
     for c in range(n_cols)
  ] 
    for r in range(n_rows)
]

如果您要“展开”内部的,看起来就像

[
  [
    int(input("Enter value for {}. row and {}. column: ".format(r + 1, 1))),
    int(input("Enter value for {}. row and {}. column: ".format(r + 1, 2))),
    # ...
    int(input("Enter value for {}. row and {}. column: ".format(r + 1, n_cols-1))),
  ]
    for r in range(n_rows)
]

进一步展开外部的会导致

[
  [
    int(input("Enter value for {}. row and {}. column: ".format(1, 1))),
    int(input("Enter value for {}. row and {}. column: ".format(1, 2))),
    # ...
    int(input("Enter value for {}. row and {}. column: ".format(1, n_cols-1))),
  ],
  [
    int(input("Enter value for {}. row and {}. column: ".format(2, 1))),
    int(input("Enter value for {}. row and {}. column: ".format(2, 2))),
    # ...
    int(input("Enter value for {}. row and {}. column: ".format(2, n_cols-1))),
  ],
  # ...
  [
    int(input("Enter value for {}. row and {}. column: ".format(n_rows-1, 1))),
    int(input("Enter value for {}. row and {}. column: ".format(n_rows-1, 2))),
    # ...
    int(input("Enter value for {}. row and {}. column: ".format(n_rows-1, n_cols-1))),
  ]
]

答案 1 :(得分:0)

列表推导是python中用于生成列表的压缩语法。如果将其重写,可能会很清楚。

一般语法为:[expression for element in list (optional: if condition)],它返回一个列表

这与写作完全相同:

new_list = []
for element in original_list:
    if (condition):   
        new_list.append(expression)

在您的情况下,您可以这样重写两个列表推导(它们是嵌套的):

arr = [[second comprehension] for r in range(n_rows)]->

arr = []
for r in range(n_rows):
    arr.append(second list)

现在,对于第二个列表理解:

second_list = []
for c in range(n_cols):
    entry = int(input("Enter value for {}. row and {}. column: ".format(r + 1, c + 1)))
    second_list.append(entry)

整个流程是:

arr = []
for r in range(n_rows):
    second_list = []
    for c in range(n_cols):
            entry = int(input("Enter value for {}. row and {}. column: ".format(r + 1, c + 1)))
            second_list.append(entry)
    arr.append(second list)