1. 请问下面代码执行后,列表 x 和 y 的内容分别是什么
- x = [[1, 2, 3],[4, 5, 6]]
- y = x.copy()
- y.append(7)
- y[1].append(8)
- print(y)
- print(x)
结果为:
[[1, 2, 3], [4, 5, 6, 8], 7]
[[1, 2, 3], [4, 5, 6, 8]]
2. 创建一个88 x 88的随机整数矩阵(二维列表)
- matrix = []
- for i in range(88):
- matrix.append([])
- for j in range(88):
- matrix[i].append(random.randint(0, 1024))
-
3.10*10杨辉三角形
重点是center函数的使用,str.center(width),此处的width为总长度
- c = []
- # 创建并初始化
- for i in range(10):
- c.append([])
- for j in range(i + 1):
- c[i].append(0)
- c[i][0] = 1
- c[i][i] = 1
- # 填数
- for i in range(2, 10):
- for j in range(1, i):
- c[i][j] = c[i - 1][j - 1] + c[i - 1][j]
- # 打印
- for i in range(10):
- lis = [str(i) for i in c[i]] # 将数值列表转化为字符列表
- s1 = ' '.join(lis) # 将字符列表中的元素用‘’连接为字符串
- print(s1.center(80)) # 居中函数,80为总长
结果如下:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
4. 请按照顺时针螺旋顺序输出矩阵中的所有元素
matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]
这个题的思路很有意思,有点点像推箱子的游戏,一次转一圈,然后更新边界值
- rows = len(matrix)
- cols = len(matrix[0])
-
- left = 0
- right = cols - 1
- top = 0
- bottom = rows - 1
-
- result = []
-
- while left <= right and top <= bottom:
- # 从左往右遍历
- for col in range(left, right + 1):
- result.append(matrix[top][col])
-
- # 从上往下遍历
- for row in range(top + 1, bottom + 1):
- result.append(matrix[row][right])
-
- if left < right and top < bottom:
- # 从右往左遍历
- for col in range(right - 1, left, -1):
- result.append(matrix[bottom][col])
-
- # 从下往上遍历
- for row in range(bottom, top, -1):
- result.append(matrix[row][left])
-
- left = left + 1
- right = right - 1
- top = top + 1
- bottom = bottom - 1
-
- print(result)