python中for循环的流程

2024-09-30 20:31:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚学过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


Tags: 代码用户inforgooglerange数组流程
2条回答

尽管共享相同的关键字,但这不是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))),
  ]
]

列表理解是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)

相关问题 更多 >