有这么一组数据类似这样
1 2
5 6
2 3
5 7
9 10
希望生成如下列表
List1=[1,2,3]
List2=[5,6,7]
List3=[9,10]
有这么一组数据类似这样
1 2
5 6
2 3
5 7
9 10
希望生成如下列表
List1=[1,2,3]
List2=[5,6,7]
List3=[9,10]
from collections import defaultdict
arr_list = [[1, 2], [5, 6], [2, 3], [5, 7], [9, 10]]
p = [i for i in range(10+1)] # 10是arr_list中最大的那个数,如果数据过于稀疏可将其离散化
def find(x):
if p[x] != x:
p[x] = find(p[x])
return p[x]
res = defaultdict(list) # 用dict不行,会出现KeyError
for item in arr_list:
fa = find(item[0])
fb = find(item[1])
if not res[fa]:
res[fa].append(item[0])
if not res[fb]:
res[fb].append(item[1])
if fa != fb:
p[fa] = fb
res[fb].extend(res[fa])
res[fa] = []
for item in res:
if res[item]:
print(res[item])