【问题标题】:Identifying collections from pair wise combinations从成对组合中识别集合
【发布时间】:2016-08-24 21:45:35
【问题描述】:

我有一个元组列表,用于识别项目之间的成对关系。

[(1,2), (2,3), (3,1), (4,5), (5,4), (6,7)]

我想查看元组并将它们折叠成唯一的集合,如下所示(可能作为哈希映射 - 任何其他有效的数据结构?):

{a: (1,2,3), b: (4,5), c(6,7)}

有没有一种算法可以有效地做到这一点 - 我现在只能想到一种蛮力方法。

希望在 Python 或 R 中实现这一点。我的原始示例有大约 2800 万个元组。

【问题讨论】:

标签: python r algorithm


【解决方案1】:

您基本上是想找到连接的组件。为此,scipy 中有一个函数connected_components。你只需要重新解释一下你的数据:

l = [(1,2), (2,3), (3,1), (4,5), (5,4), (6,7)]

from scipy.sparse.csgraph import connected_components
from scipy.sparse import csr_matrix

# make list of unique elements
uniques = list(set(list(map(lambda a: a[0], l)) + list(map(lambda a: a[1], l)))) 
# reverse index to lookup elements index
unique2index = dict([(el, i) for (i, el) in enumerate(uniques)]) 

# prepare data for csr_matrix construction
data = [1 for x in l] # value 1 -- means edge
data_i = [unique2index.get(x[0]) for x in l] # source node
data_j = [unique2index.get(x[1]) for x in l] # target node

graphMatrix = csr_matrix((data, (data_i, data_j)),shape=(len(uniques), len(uniques)))
(numComponents, labels) = connected_components(graphMatrix) # here is the work done
# interpret labels back to original elements
components = [[uniques[j] for (j,x) in enumerate(labels) if x==i] for i in range(0, numComponents)] 

print(components) # [[1, 2, 3], [4, 5], [6, 7]] is printed

【讨论】:

  • 我想指出,components = ... 步骤在输入的唯一元素数量上是二次方的。 groupby import itertools; list(map(lambda group: list([uniques[el[0]] for el in group[1]]),itertools.groupby(enumerate(labels), lambda x: x[1]))) 可能更快,但我不喜欢进行另一个导入,并且可读性....(我个人不喜欢 python,因为一个人不能一次写出可读和简短的)
猜你喜欢
  • 2011-12-12
  • 1970-01-01
  • 2018-01-13
  • 2015-10-18
  • 2013-11-29
  • 2018-04-13
  • 2023-03-20
  • 1970-01-01
  • 2018-07-15
相关资源
最近更新 更多