可以通过参考修改列表吗?

发布于 2025-01-20 12:02:50 字数 384 浏览 2 评论 0原文

我需要通过直接修改列表的引用(该函数不应返回任何值或打印任何内容,应直接通过直接修改它参考:

以下矩阵:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

亽野灬性zι浪 2025-01-27 12:02:50

您将名称矩阵绑定到一个新变量,因此它不是通过引用调用的。您可以使用代码并直接分配给切片,如下所示:

def transpose(matrix):
    matrix[:] = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]

或者,如果您想显式使用 for,则可以使用以下代码片段:

from copy import copy

def transpose(matrix):
    temp = copy(matrix)
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            matrix[i][j] = temp[j][i]

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:

def transpose(matrix):
    matrix[:] = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]

Alternatively, if you want to explicitly use for, you could use this snippet:

from copy import copy

def transpose(matrix):
    temp = copy(matrix)
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            matrix[i][j] = temp[j][i]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文