假设我有下面的嵌套列表:
L = [['John','Sayyed'], ['John' , 'Simon'] ,['bush','trump'],
['Sam','Suri','NewYork'],['Suri','Orlando','Canada']]
如何通过获得与组中至少另一个子列表具有共同元素的子列表的并集来对这些子列表进行分组?因此,对于前面的示例,结果应该是:
[['John','Sayyed','Simon'] ,['bush','trump'],
['Sam','Suri','NewYork','Orlando','Canada']]
因此,前两个子列表由于共享'John'
而连接在一起。有没有人能分享他们宝贵的想法?
发布于 2018-12-22 00:20:09
一个简单的方法
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)
看见
发布于 2018-12-21 22:31:11
要合并两个列表:
merge = lambda l1, l2: l1 + [ x for x in l2 if x not in l1 ]
为了更高效,在l1
上创建一个set
;
发布于 2019-11-27 06:05:14
您可以在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'}]
https://stackoverflow.com/questions/53886120
复制相似问题