【问题标题】:How to identify first and last node and their group from a List - Python如何从列表中识别第一个和最后一个节点及其组 - Python
【发布时间】:2019-04-02 19:12:27
【问题描述】:

我是 python 新手,正在尝试用我的数据构建图表。我有一个嵌套列表,我想根据关系分隔 2 组组,以便输出图特定于一个组。我能够得到一个完整的图表,但我想使用 python 简化 2 个图表,因为要求有数千个对象。

RelationList=[["A","B"],["B","C"],["B","D"],["D","E"],["X","Y"],["Y","Z"],["Z","U"]]

输出:

Graph 1 : 

A->B
B->C
B->D
D->E

Graph 2 :

X->Y
Y->Z
Z->U

请指导我编写代码。

【问题讨论】:

  • 问题标题与您的问题有何关系?您声称已经能够获得一个图表,因此您似乎可以访问每对的第一个和最后一个元素。您将图表分开的条件是什么?您在寻找未连接的图吗?您是否尝试过一些可用于 Python 的图形库?

标签: python arrays python-3.x python-2.7


【解决方案1】:

您可以使用数组索引来获取某些元素。数组索引工作如下:array[start:end:step]

要获取第一个节点,使用array[0],最后一个节点是array[-1],要获取连续的组,可以使用array[0:3]等范围

【讨论】:

    【解决方案2】:

    你可以这样做:
    首先为graph1创建一个包含所有可能节点的列表

    graph1_nodes = ["A", "B", "C", "D", "E"]
    

    获得该列表后,您必须对其进行迭代并将其与当前的 RelationList 进行比较,并创建一个子列表,这将是您所要求的图表之一。为此,请创建一个空列表,其中将填充 graph1 的数据

    Graph1 = []
    Graph2 = []
    for node in RelationList:
        # node is the first element of the list
        if node[0] in graph1_nodes:
            # node[0] take the first position of the element
            Graph1.append(node)
        else:
            Graph2.append(node)
    

    最后的输出是这样的:

    Graph1 = [["A","B"],["B","C"],["B","D"],["D","E"]]
    Graph2 = [["X","Y"],["Y","Z"],["Z","U"]]
    

    希望我有所帮助!

    【讨论】:

      【解决方案3】:

      您可以为此使用Union Find, or Disjoint Set 数据结构和算法。这适用于任意数量的节点和子图,并且子图是否存储在列表的封闭区域中并不重要。这非常有用,我手头总是有一个简单的实现:

      from collections import defaultdict
      class UnionFind:
          def __init__(self):
              self.leaders = defaultdict(lambda: None)
          def find(self, x):
              l = self.leaders[x]
              if l is not None:
                  l = self.find(l)
                  self.leaders[x] = l
                  return l
              return x
          def union(self, x, y):
              lx, ly = self.find(x), self.find(y)
              if lx != ly:
                  self.leaders[lx] = ly
          def get_groups(self):
              groups = defaultdict(set)
              for x in self.leaders:
                  groups[self.find(x)].add(x)
              return list(groups.values())
      

      向您的RelationList申请:

      RelationList=[["A","B"],["B","C"],["B","D"],["D","E"],["X","Y"],["Y","Z"],["Z","U"]]
      uf = UnionFind()
      for a, b in RelationList:
          uf.union(a, b)
      print(uf.get_groups()) # [{'C', 'A', 'D', 'B', 'E'}, {'U', 'Z', 'Y', 'X'}]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-20
        • 1970-01-01
        • 1970-01-01
        • 2020-03-16
        • 2015-09-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多