我有以下内容:
[[1, 2], [3], [4,5], [6,1], [5,3,4], [4,7]]
我试图将它们组合在一起,这样如果一个数字在另一个数组中,我就组合了这些数组。输出应为:
[[1,2,6],[3,4,5,7]]
关于如何在Python中执行此操作的任何想法?
答案 0 :(得分:0)
这就是我要做的事情:
>>> L = [[1, 2], [3], [4,5], [6,1], [5,3,4], [4,7]]
>>> L = [set(e) for e in L]
>>> combined = []
>>> while L:
... group = L.pop()
... for other in L:
... if group.intersection(other):
... group.update(other)
... L = [e for e in L if not group.intersection(e)]
... combined.append(group)
...
>>> combined
[set([3, 4, 5, 7]), set([1, 2, 6])]
首先将原始列表中的每个组转换为设置,然后贪婪地将元素合并为一组。