2015-11-09 27 views
-5

我想從2維列表生成一個字典。如何從2維數組中生成字典?

字典的關鍵字應該是數組位置(x,y)的索引。該值應該是一個包含此數組位置的所有鄰居(上,下,右,左)的列表。該值是鄰居的位置。的4×4 2維列表的

實施例:

輸入:

[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] 

輸出:

graph = { 
    '0,0': ["0,1", "1,0"], 
    '0,1': ["0,0", "1,1", "0,2"], 
    '0,2': ["0,1", "0,3", "1,2"], 
    '0,3': ["0,2", "1,3"], 

    '1,0': ["0,0", "1,1", "2,0"], 
    '1,1': ["0,1", "1,0", "2,1", "1,2"], 
    '1,2': ["0,2", "1,1", "2,2", "1,3"], 
    '1,3': ["0,3", "1,2", "2,3"], 

    '2,0': ["1,0", "3,0", "2,1"], 
    '2,1': ["2,0", "3,1", "2,2", "1,1"], 
    '2,2': ["1,2", "2,1", "3,2", "2,3"], 
    '2,3': ["1,3", "2,2", "3,3"], 

    '3,0': ["2,0", "3,1"], 
    '3,1': ["2,1", "3,0", "3,2"], 
    '3,2': ["2,2", "3,1", "3,3"], 
    '3,3': ["2,3", "3,2"], 
} 
+2

那麼你有什麼試過,究竟是什麼問題呢? – jonrsharpe

+0

我認爲可能有一個簡單的解決方案,但我找不到任何人。 – gustavgans

+2

... *「那麼你試過了什麼,它的問題究竟是什麼?」*如果你有**工作代碼**,你認爲可以改進,請參閱[codereview.se]。如果你沒有代碼,那就寫一些。 – jonrsharpe

回答

0

相信這種算法將做

grid = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] #input 

dic = dict() 
for i in xrange(len(grid)): 
    for j in xrange(len(grid[0])): 
     x = [] 
     for k in [(0, 1), (1, 0), (-1, 0), (0, -1)]: 
      if 0 <= i + k[0] < len(grid) and 0 <= j + k[1] < len(grid[0]): 
       x.append((i + k[0], j + k[1])) 
     dic[(i, j)] = x 

字典dic就是你想要的

+0

非常感謝你! – gustavgans

+0

ohh列表中的最後一項是錯誤的! – gustavgans

0

這對我現在有效。我對任何改進保持開放。

size_y = 4 
size_x = 4 

l = [[0 for x in range(size_y)] for x in range(size_x)] 
d = {} 

for x in range(size_x): 
    for y in range(size_y): 
     key = "{},{}".format(x, y) 
     # edges 
     if x == 0 and y == 0: 
      l = ["0,1", "1,0"] 
     elif x == size_x-1 and y == size_y-1: 
      l = ["{},{}".format(x,y-1), "{},{}".format(x-1,y)] 
     elif x == size_x-1 and y == 0: 
      l = ["{},{}".format(x-1,y),"{},{}".format(x,y+1)] 
     elif x == 0 and y == size_y-1: 
      l = ["{},{}".format(0,y-1),"{},{}".format(x+1,y)] 
     else: 
      l = [] 
      #N x y-1 
      if y-1 >= 0: 
       l.append("{},{}".format(x, y-1)) 
      #O x+1 y 
      if x+1 < size_x: 
       l.append("{},{}".format(x+1, y)) 
      #S x y+1 
      if y+1 < size_y: 
       l.append("{},{}".format(x, y+1)) 
      #W x-1 y 
      if x-1 >= 0: 
       l.append("{},{}".format(x-1, y)) 
     d[key] = l 

print(d)