2014-11-04 32 views
0

我想定義一個相當簡單的函數矩陣交換兩個項目,目前我有以下代碼的函數:定義作用於矩陣在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一起使用。

+0

這是無效的Python語法 - 你應該看看https://docs.python.org/2/tutorial/controlflow.html#defining-functions – jonrsharpe 2014-11-04 15:14:47

+1

Python無法知道'current'來自'矩陣[3] [2]'。 「當前」甚至可能同時出現在不同矩陣的不同位置。你必須明確地傳遞矩陣和索引。 – interjay 2014-11-04 15:16:14

回答

0

我不太清楚,如果這是你想要的,但它至少是工作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被換。

0

擴展在@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]向上移動一行,而不是移動到左側。