如何在python中找到节点之间的邻居

时间:2014-09-16 02:58:23

标签: python list

o 1
1 2
2 3
3 4
4 0 
4 1
5 3

我有两个节点列表如上所示 我怎样才能找到每个节点和输出的邻居可以显示为[[1,4],[0,2,4],[1,3],[2,4,5],[0,1,3] ],[3]]

1 个答案:

答案 0 :(得分:0)

#!/usr/bin/env python3
# nodes <infile
#
# Read in lists of node neighbors, and output complete list of all neighbors
#
# nodeA nodeB
# nodeC nodeD

class NodeList:
  def __init__(self):
    self.nodes = {}
    self.groups = 0

  def add_pair(self, n1, n2):       # add a pair of nodes
    self.add_node(n1, n2)           # they are neighbors
    self.add_node(n2, n1)           # to each other

  def add_node(self, n1, n2):
    if n1 not in self.nodes:
      self.nodes[n1] = []
    if n2 not in self.nodes[n1]:    # add n2 only if not already a link
      self.nodes[n1].append(n2)
      self.groups += 1

  def neighbors(self):
    return list(map(lambda k: sorted(self.nodes[k]), sorted(self.nodes.keys())))

nodes = NodeList()
while True:
  try:
    line = input()
    nums = [int(x) for x in line.split()]
    if len(nums) > 0:
      n1 = nums.pop(0)
      for nx in nums:
        nodes.add_pair(n1, nx)
  except EOFError:
    break

print(nodes.neighbors())

exit

数据文件:

$ cat in-nodes
0 1
1 2
2 3
3 4
4 0
4 1
5 3

跑步:

$ ./nodes.py <in-nodes
[[1, 4], [0, 2, 4], [1, 3], [2, 4, 5], [0, 1, 3], [3]]