如何在Python中组合数组?
我有以下资料:如何在Python中组合数组?,python,arrays,Python,Arrays,我有以下资料: [[1, 2], [3], [4,5], [6,1], [5,3,4], [4,7]] 我试图组合这些,这样如果一个数字在另一个数组中,我就组合这些数组。输出应如下所示: [[1,2,6],[3,4,5,7]] 关于如何在Python中实现这一点,有什么想法吗?以下是我要做的: >>> L = [[1, 2], [3], [4,5], [6,1], [5,3,4], [4,7]] >>> L = [set(e) for e in L] &g
[[1, 2], [3], [4,5], [6,1], [5,3,4], [4,7]]
我试图组合这些,这样如果一个数字在另一个数组中,我就组合这些数组。输出应如下所示:
[[1,2,6],[3,4,5,7]]
关于如何在Python中实现这一点,有什么想法吗?以下是我要做的:
>>> 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])]
这首先将原始列表中的每个组转换为set,然后贪婪地将元素合并到组中。您是否尝试解决此问题?你尝试了什么?不清楚你所说的“如果数字在另一个数组中”是什么意思。如果另一个数组中有什么数字?数组组合的规则是什么?@merlin2011,我认为如果两个子列表共享一个公共数字,那么应该组合输出是否必须排序?另外,看起来您希望删除重复项。您可以使用集合。非常感谢@jterrace!我正要发这个,但你比我快。没问题,祝你好运!