【问题标题】:Combine lists with common elements将列表与常见元素结合起来
【发布时间】:2019-05-22 00:07:00
【问题描述】:

假设我有以下嵌套列表:

L = [['John','Sayyed'], ['John' , 'Simon'] ,['bush','trump'],
     ['Sam','Suri','NewYork'],['Suri','Orlando','Canada']]

如何通过获取与组内至少另一个子列表具有共同元素的子列表的联合来对这些子列表进行分组?所以对于前面的例子,结果应该是:

[['John','Sayyed','Simon'] ,['bush','trump'],
 ['Sam','Suri','NewYork','Orlando','Canada']]

因此,前两个子列表在共享'John' 时被加入。 有人可以分享他们的宝贵想法吗?

【问题讨论】:

    标签: python list networkx


    【解决方案1】:

    在许多情况下,将问题建模为图形可以使相当复杂的任务变得更加容易。在这种情况下,从图论的角度来看,我们要寻找的是图的connected components。

    因此,解决此问题的一种简单方法是使用NetworkX 生成一个图形,并使用add_edges_from 将您的列表添加为图形边缘。然后使用connected_components,它将精确地为您提供图中连接组件集的列表:

    import networkx as nx 
    
    L = [['John','Sayyed'], ['John' , 'Simon'] ,['bush','trump']]
    
    G=nx.Graph()
    G.add_edges_from(L)
    list(nx.connected_components(G))
    
    [{'John', 'Sayyed', 'Simon'}, {'bush', 'trump'}]
    

    包含多个 (>2) 项的子列表怎么样?

    如果子列表包含多个2 元素,您可以将它们添加为路径,而不是使用nx.add_path 的节点,因为它们可以连接多个节点:

    L = [['John','Sayyed'], ['John' , 'Simon'] ,['bush','trump'],
         ['Sam','Suri','NewYork'],['Suri','Orlando','Canada']]
    
    G=nx.Graph()
    for l in L:
        nx.add_path(G, l)
    list(nx.connected_components(G))
    
    [{'John', 'Sayyed', 'Simon'},
     {'bush', 'trump'},
     {'Canada', 'NewYork', 'Orlando', 'Sam', 'Suri'}]
    

    我们也可以用nx.draw可视化这些连接的组件:

    pos = nx.spring_layout(G, scale=20, k=2/np.sqrt(G.order()))
    nx.draw(G, pos, node_color='lightgreen', node_size=1000, with_labels=True)
    


    关于连通分量(图论)

    更详细的解释在connected components:

    在图论中,无向图的连通分量(或只是分量)是一个子图,其中任意两个顶点通过路径相互连接,并且不与超图中的其他顶点相连

    因此,基本上,这段代码创建了一个图表,其中包含列表中的边,其中每条边由两个值组成 u,v 其中u 和 v 将是由该边连接的节点。

    因此,具有至少一个具有公共元素的子列表的子列表的并集可以转换为图论问题,因为所有节点都可以通过现有路径在彼此之间到达。

    【讨论】:

    • 有趣的方法,请解释一下这是做什么的
    • 如果子列表有两个以上的元素会怎样?
    • @Aiyaz 更新了一个更通用的情况,即具有超过 2 个元素的子列表
    【解决方案2】:

    一个简单的方法

    L = [['John','Sayyed'], [ 'John' , 'Simon'] ,['bush','trump']]
    L[0].extend([x for x in L[1] if x not in L[0]])
    L.pop(1)
    print(L) 
    

    见

    List Comprehensions

    Append vs Extend

    【讨论】:

      【解决方案3】:

      如果顺序很重要且列表很大,你可以使用这两种方法:

       l = [['john', 'sayyid'], ['john', 'simon'], ['b', 't']]
      
       def join(l1, l2):
           mset = set(l1)
           result = l1[:] # deep copy
           for each in l2:
               if each in mset:
                   continue
               else:
                   result.append(each)
           return result
      

      要在主列表中合并,您只需按其排名调用列表并弹出原始列表:

      l1 = l.pop(0)
      l2 = l.pop(0)
      l.insert(0, join(l1, l2))
      >>> l:
      [['john', 'sayyid', 'simon'], ['b', 't']]
      

      【讨论】:

        【解决方案4】:

        要合并 2 个列表:

        merge = lambda l1, l2: l1 + [ x for x in l2 if x not in l1 ]
        

        为了更高效,请在l1 上创建set;

        【讨论】:

          【解决方案5】:

          你可以在networkx中使用函数connected_components:

          import networkx as nx 
          ​
          L = [['John','Sayyed'], ['John' , 'Simon'] ,['bush','trump'],
               ['Sam','Suri','NewYork'],['Suri','Orlando','Canada']]
          ​
          G = nx.Graph()
          ​
          for i in L:
              G.add_path(i)
          ​
          lst = list(nx.connected_components(G))
          print(lst)
          

          输出:

          [{'John', 'Sayyed', 'Simon'},
           {'bush', 'trump'},
           {'Canada', 'NewYork', 'Orlando', 'Sam', 'Suri'}]
          

          【讨论】:

            猜你喜欢
            • 2020-11-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-10-27
            • 2021-10-29
            • 2014-04-01
            相关资源
            最近更新 更多