![](/img/trans.png)
[英]Need help defining a function and then adding it to a matrix in Python
[英]defining a function acting on a matrix in python
我想定义一个相当简单的函数来交换矩阵中的两个条目,目前我有以下代码:
def swap (n[a][b] ,direction):
if direction==1: #to the left
entry=n[a][b]
n[a][b]=n[a-1][b]
n[a-1][b]=entry
我正在努力寻找一种方法来使它,以便当我输入变量(例如current
(其中current =matrix[3][2]
))时, if
子句的内容在目标上以a=3 ,b=2
起作用矩阵。
我不太确定这是否是您想要的,但至少它在运行python代码:
import numpy as np
def swap(M, a, b, direction):
if direction == 1:
entry = M[a,b]
M[a,b] = M[a-1,b]
M[a-1,b] = entry
#create a test matrix
np.random.seed(10)
n = np.random.rand(10, 100, size=(3,2))
print n
n = swap(n,2,1,1)
print n
输出:
[[19 25]
[74 38]
[99 39]]
[[19 25]
[74 39]
[99 38]]
因此38和39被交换了。
扩展@interjay注释,这是一个工作函数(假设矩阵是列表列表):
def swap(m, r, c, direction):
if direction == 1:
m[r][c], m[r-1][c] = m[r-1][c], m[r][c]
参数:
m
是您要作用的矩阵, r
是要交换的元素的一行, c
是您要交换的元素的列, direction
是交换的方向。 用法示例:
A = [[1, 2], [3, 4]]
print A
swap(A, 1, 1, 1)
print A
输出:
[[1, 2], [3, 4]]
[[1, 4], [3, 2]]
还要注意,通常(但不是必需),第一个索引对应于行或行,第二个索引对应于列。 在这种情况下,将n[a][b]
与代码中的n[a-1][b]
交换等效于将元素n [a] [b]向上移动一行,而不是向左移动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.