可以通过参考修改列表吗?
我需要通过直接修改列表的引用(该函数不应返回任何值或打印任何内容,应直接通过直接修改它参考:
以下矩阵:
1 2 3
4 5 6
7 8 9
不接受
1 4 7
2 5 8
3 6 9
我的代码:
def transpose(matrix):
matrix = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
我不明白...此代码仅修改列表的值,而不是参考
? “ python的“ ...”功能)。
要使用
I need to create a function that transpose a matrix (to basically transform rows into columns, and columns into rows) by modifying directly the reference of the list (the function should not return any value, or print anything, it should be modified directly through the reference :
The following matrix :
1 2 3
4 5 6
7 8 9
should be transformed into
1 4 7
2 5 8
3 6 9
However, my code is not accepted :
def transpose(matrix):
matrix = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
I can't understand why... Is this code modifying only the value of the list, and not the reference ?
Any suggestion ? (I need to use "for ... " function from python).
Thank you in advance !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将名称矩阵绑定到一个新变量,因此它不是通过引用调用的。您可以使用代码并直接分配给切片,如下所示:
或者,如果您想显式使用 for,则可以使用以下代码片段:
You bind the name matrix to a new variable, so it's not call by reference. You could use your code and directly assign to the slice like so:
Alternatively, if you want to explicitly use for, you could use this snippet: