python - 我写了这段代码,但我的输出不是应该是 2D 的,我不知道如何修复它
问题描述
我完全编写了我的代码,但我没有从问题中得到预期的输出。当我输入我的值时,由于某种原因它们不在二维列表中。
功能:
def matrix_rotate_right(a):
b = []
for i in range(len(a[0])):
b.append([])
for j in range(len(a) - 1, -1, -1):
b[i].append(a[j][i])
return b
t01.py
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
b = matrix_rotate_right(a)
print(b)
问题:
Write and test the following function:
def matrix_rotate_right(a):
"""
-------------------------------------------------------
Returns a copy of a 2D matrix rotated to the right.
a must be unchanged.
Use: b = matrix_rotate_right(a)
-------------------------------------------------------
Parameters:
a - a 2D list of values (2d list of int/float)
Returns:
b - the rotated 2D list of values (2D list of int/float)
-------------------------------------------------------
"""
Add this function to the PyDev module functions.py. Test it from t01.py.
示例运行:
Given the following 2D matrix:
1 2 3
4 5 6
7 8 9
10 11 12
Rotating it to the right produces the following matrix:
10 7 4 1
11 8 5 2
12 9 6 3
我得到的输出:
[[10, 7, 4, 1], [11, 8, 5, 2], [12, 9, 6, 3]]
解决方案
Your4 功能可以满足您的需求。
您只需要格式化输出
def matrix_rotate_right(a):
b = []
for i in range(len(a[0])):
b.append([])
for j in range(len(a) - 1, -1, -1):
b[i].append(a[j][i])
return b
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
b = matrix_rotate_right(a)
for tuple in b:
print(format(' '.join(map(str,tuple))))
推荐阅读
- html - 如何访问 HTML 中的根目录?(使用 / 不起作用)
- c# - 在环境变量 ASP.Net MVC 应用程序中正确存储数据库连接字符串
- c++ - 类继承问题
- mongodb - 如何在 mongodb 查询或通过 mongoose 检索 n 级嵌套类别树
- python -
我的分页器生病了吗?我在做什么错? - python - nginx-gunicorn Flask 应用程序未指向我在 CentoOS 7 上的应用程序目录
- excel - 努力在网页上单击带有 VBA 代码的继续按钮
- python - 使用函数从二维数组转换到不同坐标系的最有效方法,然后对结果孔进行插值
- python - 在 Python 3 中给定两个值,加速分配概率密度
- ruby-on-rails - 从不同的 Active Record 模型/表中检索一条数据