我试图找到一种方法来查找列表列表中给定节点的所有邻居。该数组如下所示:
0,2,4,1,6,0,0
2,0,0,0,5,0,0
4,0,0,0,5,5,0
1,0,0,0,1,1,0
6,5,0,1,0,5,5
0,0,5,1,5,0,0
0,0,0,0,5,0,0
到目前为止,我的代码是:
#!/usr/bin/python
#holds all source nodes
source = []
#read in and store the matrix
def create_matrix(file):
with open('network.txt') as f:
Alist = []
for line in f:
part = []
for x in line.split(','):
part.append(int(x))
Alist.append(part)
return Alist
def check_neighbours(Alist):
i = iter(Alist)
item = i.next()
source.append(item)
print source
file = ("F:/media/KINGSTON/Networking/network.txt")
Alist = create_matrix(file)
check_neighbours(Alist)
显然这只输出矩阵的第一行,但我想要一些不同的东西。例如,我将从节点[0,0]开始,它是0,然后找到[0,1]和[1,0]。但是如果我不在矩阵的边缘,我还需要查看3x3半径。我知道如何找到当前节点右边的下一个邻居,但我真的不确定如何找到包含对角节点的节点旁边的任何内容。
答案 0 :(得分:5)
你想要一个8邻居算法,它实际上只是列表列表中的一系列索引。
# i and j are the indices for the node whose neighbors you want to find
def find_neighbors(m, i, j, dist=1):
return [row[max(0, j-dist):j+dist+1] for row in m[max(0, i-1):i+dist+1]]
然后可以通过以下方式调用:
m = create_matrix(file)
i = some_y_location
j = some_x_location
neighbors = find_neighbors(m, i, j)
没有列表压缩的实现:
def find_neighbors(m, i, j, dist=1):
neighbors = []
i_min = max(0, i-dist)
i_max = i+dist+1
j_low = max(0, j-dist)
j_max = j+dist+1
for row in m[i_min:i_max]:
neighbors.append(row[j_min:j_max])
return neighbors
您需要对i / j_min进行最大调用以避免负索引,但是上限值太大会自动由列表切片处理。
如果您希望将这些行列表作为单个元素列表,则需要添加:
neighbors = [elem for nlist in neighbors for elem in nlist]
这使列表清单变得扁平化。
如果你想要邻居的指示(可能有更清洁的解决方案):
def find_neighbor_indices(m, i, j, dist=1):
irange = range(max(0, i-dist), min(len(m), i+dist+1))
if len(m) > 0:
jrange = range(max(0, j-dist), min(len(m[0]), j+dist+1))
else:
jrange = []
for icheck in irange:
for jcheck in jrange:
# Skip when i==icheck and j==jcheck
if icheck != i or jcheck != j:
neighbors.append((icheck, jcheck))
return neighbors