【发布时间】:2016-10-07 20:52:20
【问题描述】:
从链接对的列表中,我想将这些对组合成公共 ID 组,这样我就可以将 group_ids 写回数据库,例如:
UPDATE table SET group = n WHERE id IN (...........);
例子:
[(1,2), (3, 4), (1, 5), (6, 3), (7, 8)]
变成
[[1, 2, 5], [3, 4, 6], [7, 8]]
允许:
UPDATE table SET group = 1 WHERE id IN (1, 2, 5);
UPDATE table SET group = 2 WHERE id IN (3, 4, 6);
UPDATE table SET group = 3 WHERE id IN (7, 8);
和
[(1,2), (3, 4), (1, 5), (6, 3), (7, 8), (5, 3)]
变成
[[1, 2, 5, 3, 4, 6], [7, 8]]
允许:
UPDATE table SET group = 1 WHERE id IN (1, 2, 5, 3, 4, 6);
UPDATE table SET group = 2 WHERE id IN (7, 8);
我已经编写了一些有效的代码。我传入一个元组列表,其中每个元组是一对链接的 id。我返回一个列表列表,其中每个内部列表都是一个公共 id 的列表。
我遍历元组列表并将每个元组元素分配给组,如下所示:
- 如果 a 和 b 都不在列表中,则创建一个新列表,附加 a 和 b 并将新列表附加到列表列表中
- 如果 a 在某个组中但 b 不在,则将 b 添加到 a 组中
- 如果 b 在组中但 a 不在组中,则将 a 添加到 b 组中
- 如果 a 和 b 已经在不同的组中,则合并 a 和 b 组
- 如果 a 和 b 已经在同一个组中,则什么也不做
我期待数百万个链接对,我期待数十万个 gropus 和数十万个组成员。所以,我需要快速的算法,我正在寻找一些真正有效的代码的建议。虽然我已经实现了这个来构建列表列表,但我对任何事情都持开放态度,他们的关键是能够构建上述 SQL 以将组 ID 返回到数据库。
def group_pairs(list_of_pairs):
"""
:param list_of_pairs:
:return:
"""
groups = list()
for pair in list_of_pairs:
a_group = None
b_group = None
for group in groups:
# find what group if any a and b belong to
# don't bother checking if a group already found
if a_group is None and pair[0] in group:
a_group = group
# don't bother checking if b group already found
if b_group is None and pair[1] in group:
b_group = group
# if a and b found, stop looking
if a_group is not None and b_group is not None:
break
if a_group is None:
if b_group is None:
# neither a nor b are in a group; create a new group and
# add a and b
groups.append([pair[0], pair[1]])
else:
# b is in a group but a isn't, so add a to the b group
b_group.append(pair[0])
elif a_group != b_group:
if b_group is None:
# a is in a group but b isn't, so add b to the a group
a_group.append(pair[1])
else:
# a and b are in different groups, add join b to a and get
# rid of b
a_group.extend(b_group)
groups.remove(b_group)
elif a_group == b_group:
# a and b already in same group, so nothing to do
pass
return groups
【问题讨论】: