2013-04-26 96 views
2

所以,這裏的問題是,我有一個二維的字符'T'和'F'列表,並給出座標,我需要得到它的所有鄰居。我有這樣的:python,在一個二維列表中找到鄰居

from itertools import product, starmap 
x, y = (5, 5) 
cells = starmap(lambda a, b: (x + a, y + b), product((0, -1, +1), (0, -1, +1))) 

determining neighbors of cell two dimensional list但它只會給我coordinantes的名單,所以我還是後記獲取的值。 (5,5)將返回F,T,F,F,...而不是(5,4),(5,6),(4, 5),(4,4)...有沒有一個快速的方法來做到這一點?該solutin可以包括其他的結構比list保持初始信息

+0

你能/願意使用Numpy嗎? – YXD 2013-04-26 21:23:07

+0

是的,我還不知道它,但我可以學習 – EasilyBaffled 2013-04-26 21:34:28

回答

6

以下應該工作,只是一個小的適應當前代碼:

from itertools import product, starmap, islice 

def findNeighbors(grid, x, y): 
    xi = (0, -1, 1) if 0 < x < len(grid) - 1 else ((0, -1) if x > 0 else (0, 1)) 
    yi = (0, -1, 1) if 0 < y < len(grid[0]) - 1 else ((0, -1) if y > 0 else (0, 1)) 
    return islice(starmap((lambda a, b: grid[x + a][y + b]), product(xi, yi)), 1, None) 

例如:

>>> grid = [[ 0, 1, 2, 3], 
...   [ 4, 5, 6, 7], 
...   [ 8, 9, 10, 11], 
...   [12, 13, 14, 15]] 
>>> list(findNeighbors(grid, 2, 1)) # find neighbors of 9 
[8, 10, 5, 4, 6, 13, 12, 14] 
>>> list(findNeighbors(grid, 3, 3)) # find neighbors of 15 
[14, 11, 10] 

爲了清楚起見,下面是一些沒有itertools魔法的等效代碼:

def findNeighbors(grid, x, y): 
    if 0 < x < len(grid) - 1: 
     xi = (0, -1, 1) # this isn't first or last row, so we can look above and below 
    elif x > 0: 
     xi = (0, -1)  # this is the last row, so we can only look above 
    else: 
     xi = (0, 1)  # this is the first row, so we can only look below 
    # the following line accomplishes the same thing as the above code but for columns 
    yi = (0, -1, 1) if 0 < y < len(grid[0]) - 1 else ((0, -1) if y > 0 else (0, 1)) 
    for a in xi: 
     for b in yi: 
      if a == b == 0: # this value is skipped using islice in the original code 
       continue 
      yield grid[x + a][y + b] 
+0

謝謝,現在,如果您想回答,還有一個數據結構,如numpy或blist會更好。我真的不知道這兩個我只知道他們存在 – EasilyBaffled 2013-04-26 22:08:27

+0

@EasilyBaffled:你可能想爲此創建一個單獨的問題。但是,在任何人都可以回答之前,你必須定義「更好地工作」的含義。這是正確的,非常容易理解,並且在給定您的小數據量的情況下幾乎可以肯定速度更快。那麼,怎麼會比這更好呢? – abarnert 2013-04-26 22:53:27

+0

我不喜歡在標記答案後返回,但星圖((lambda a,b:grid [x + a] [y + b])可能遭受索引超出範圍錯誤,任何人都知道如何調整那麼? – EasilyBaffled 2013-05-01 15:59:27