我怎样才能找到给定列表中的邻居?

时间:2014-09-28 08:09:21

标签: python graph-algorithm nearest-neighbor

from, to
0, 1
1, 2
2, 3
3, 4
4, 0 
4, 1
5, 3

我有一个边缘列表(由两个节点列表组成),如上所示,在文本FILE中给出。如何找到每个节点的邻居,输出可以显示为[[1,4],[0 ,2,4],[1,3],[2,4,5],[0,1,3],[3]] 所以[1,4]是0的邻居,而[0,2,4]是1的邻居,依此类推

2 个答案:

答案 0 :(得分:2)

import collections

d = collections.defaultdict(set)
with open('filename') as f:
    for line in f:
        x, y = map(int, line.rstrip().split(", "))
        d[x].add(y)
        d[y].add(x)

#defaultdict(<type 'set'>, {0: set([1, 4]), 1: set([0, 2, 4]), 2: set([1, 3]), 3: set([2, 4, 5]), 4: set([0, 1, 3]), 5: set([3])})

答案 1 :(得分:0)

x = [ 0,1,2,3,4,4,5]
y = [ 1,2,3,4,0,1,3]

选项1:

l1 = [(x[i] , y[i]) for i in range(len(x))]
l2 = [(y[i] , x[i]) for i in range(len(x))]
l1.extend(l2)

[[l[0] for l in l1 if l[1] == j] for j in range(5)]

选项2:

使用字典:

for i in range(len(x)):
  if not d.has_key(x[i]):
    d[x[i]] = []
  d[x[i]].append(y[i])
  if not d.has_key(y[i]):
    d[y[i]] = []
  d[y[i]].append(x[i])


print d