列表与公共元素的并集

2024-10-02 10:28:45 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下嵌套列表:

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

我如何通过得到子列表的并集来对这些子列表进行分组,这些子列表至少与组中的另一个子列表具有公共元素?因此对于前面的例子,结果应该是:

^{pr2}$

因此,前两个子列表在它们共享'John'时被连接起来。 有人能分享一下他们的宝贵想法吗?在


Tags: 元素列表samjohn例子simoncanadanewyork
3条回答

nx.connected_components

您可以使用networkx来实现这一点。生成一个图,并使用^{}添加列表作为图的边。然后使用^{},它将精确地为您提供图中连接组件的集合列表:

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^{},并将其用作网络边缘:

^{pr2}$

我们还可以用^{}将这些连接的组件形象化:

pos = nx.spring_layout(G, scale=20)
nx.draw(G, pos, node_color='lightblue', node_size=500, with_labels=True)


enter image description here


详细信息

关于connected components的更详细说明:

In graph theory, a connected component (or just component) of an undirected graph is a subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the supergraph

因此,本质上,这段代码创建了一个图,其中每个边由两个值组成u,v,其中u和{}将由这条边连接起来。在

因此,子列表与至少一个子列表和一个公共元素的合并可以转化为图论问题,因为所有节点都可以通过现有路径到达。在

合并两个列表:

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

为了提高效率,请在l1上创建set

如果order很重要且列表很大,可以使用以下两种方法:

 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

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

^{pr2}$

相关问题 更多 >

    热门问题