【发布时间】:2021-11-02 19:18:04
【问题描述】:
我正在寻找一种快速的方法来遍历集合列表,并通过找到与列表中至少共享一个元素的任何其他元素的联合来扩展每个集合。
例如,假设我有四行数据,其中每一行对应一组唯一的元素
0, 5, 101
8, 9, 19, 21
78, 79
5, 7, 63, 64
第一行和最后一行有相交元素 5,所以在执行我的操作后我想要联合
0, 5, 7, 63, 64, 101
8, 9, 19, 21
78, 79
0, 5, 7, 63, 64, 101
现在,我几乎可以用两个循环做到这一点:
def consolidate_list(arr):
"""
arr (list) : A list of lists, where the inner lists correspond to sets of unique integers
"""
arr_out = list()
for item1 in arr:
item_additional = list() # a list containing all overlapping elements
for item2 in arr:
if len(np.intersect1d(item1, item2)) > 0:
item_additional.append(np.copy(item2))
out_val = np.unique(np.hstack([np.copy(item1)] + item_additional)) # find union of all lists
arr_out.append(out_val)
return arr_out
这种方法的问题是它需要运行多次,直到输出停止变化。由于输入可能是锯齿状的(即每组不同数量的元素),我看不到向量化此函数的方法。
【问题讨论】:
-
想到的第一个想法:(1)构建一个图,其中每个顶点都是您的集合之一,并且如果两个集合具有共同的元素,则两个集合共享一条边。 (2) 识别图的连通分量。 (3) 合并属于同一个连通分量的所有集合。您可以考虑使用模块
networkx来构建图并识别连接的组件。 -
我已修正错字。谢谢!
标签: python arrays algorithm performance intersection