我刚学过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)]
尽管共享相同的关键字,但这不是
for
循环;这是一个嵌套在另一个列表理解中的列表理解。因此,您需要首先评估内部列表:如果你要“展开”内部的一个,它会像
再把外面的展开
列表理解是python中用于生成列表的压缩语法。如果你重写这个,它可能会非常清楚
一般语法是:
[expression for element in list (optional: if condition)]
,它返回一个列表这与写作完全相同:
在您的例子中,您可以重写两个列表理解(它们是嵌套的),如下所示:
arr=
[[second comprehension] for r in range(n_rows)]
->现在,对于第二个列表:
整个流程是:
相关问题 更多 >
编程相关推荐