代码如下:
n = 5
matrix1 = [ [1] * 3 for q in range(n)]
print(matrix1)
for q in range(n):
matrix2 = [ [2] * q]
print(matrix2)
>>>
[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]
[[]]
[[2]]
[[2, 2]]
[[2, 2, 2]]
[[2, 2, 2, 2]]
n = 5
matrix1 = [ [1] * n for q in range(n)]
print(matrix1)
for q in range(n):
matrix2 = [ [2] * n]
print(matrix2)
>>>
[[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]
[[2, 2, 2, 2, 2]]
[[2, 2, 2, 2, 2]]
[[2, 2, 2, 2, 2]]
[[2, 2, 2, 2, 2]]
[[2, 2, 2, 2, 2]]
关于代码的理解:
第一个for循环是在列表内部重复执行5次的结果,生成matrix1;
第二个for循环是matrix2赋值这件事情执行了5次.
注:[[ ]] 表示 列表嵌套。
参考网址:https://www.runoob.com/python3/python3-list.html