作者:薇薇VS安安北_396 | 来源:互联网 | 2022-12-06 13:32
我需要一种有效的方法来合并节点列表(整数对).
只有当对中有一个公共号码并且公共号码位于第一个或最后一个位置(否则它已经全部连接)时,才会发生合并.
例如:
mylist = [[4, 3], [6, 3]]
merge_links(mylist) # should output [4, 3, 6]
另一个例子:
mylist = [[4, 3], [6, 3], [6, 4]]
merge_links(mylist)
# should output again [4, 3, 6] because both 6 and 4 allready exist in array.
又一个例子:
mylist = [[4, 3], [6, 3], [6, 4], [6, 2], [7, 4], [4, 9]]
merge_links(mylist)
# should output [7, 4, 3, 6, 2]
# [4, 3] ?
# [4, 3] + [6, 3] ? -> [4, 3, 6]
# [4, 3, 6] + [6, 3] ? both 6 and 3 exist in [4, 3, 6]
# [4, 3, 6] + [6, 4] ? both 6 and 4 exist in [4, 3, 6]
# [4, 3, 6] + [6, 2] ? -> [4, 3, 6, 2]
# [4, 3, 6, 2] + [7, 4] ? -> [7, 4, 3, 6, 2]
# [7, 4, 3, 6, 2] + [4, 9] ? 4 is allready connected "7-4-3"!
目前我正在使用:
def merge_links(a, b):
inter = np.intersect1d(a, b, True)
a = set(a) - set(inter)
b = set(b) - set(inter)
n = np.unique(list(a) + list(inter) + list(b))
return n
但它不适用于上述限制