假设我有以下嵌套列表:
L = [['John','Sayyed'], ['John' , 'Simon'] ,['bush','trump'],
['Sam','Suri','NewYork'],['Suri','Orlando','Canada']]
我如何通过得到子列表的并集来对这些子列表进行分组,这些子列表至少与组中的另一个子列表具有公共元素?因此对于前面的例子,结果应该是:
^{pr2}$
因此,前两个子列表在它们共享'John'
时被连接起来。
有人能分享一下他们的宝贵想法吗?在
Tags:
nx.connected_components
您可以使用} 添加列表作为图的边。然后使用^{} ,它将精确地为您提供图中连接组件的集合列表:
networkx
来实现这一点。生成一个图,并使用^{包含多个项目的子列表
如果子列表包含多于} ,并将其用作网络边缘:
^{pr2}$2
元素,则可以从每个子列表中获取所有长度2
^{我们还可以用^{} 将这些连接的组件形象化:
详细信息
关于connected components的更详细说明:
因此,本质上,这段代码创建了一个图,其中每个边由两个值组成}将由这条边连接起来。在
u,v
,其中u
和{因此,子列表与至少一个子列表和一个公共元素的合并可以转化为图论问题,因为所有节点都可以通过现有路径到达。在
合并两个列表:
为了提高效率,请在
l1
上创建set
如果order很重要且列表很大,可以使用以下两种方法:
要在主列表中合并,您只需按级别调用列表并弹出原始列表:
^{pr2}$相关问题 更多 >
编程相关推荐