我在python中有一个类似于下面的列表(真正的列表非常庞大,我不能仅通过查看来实现):
original1=[['email', 'tel', 'fecha', 'descripcion', 'categ'],
['a@gmail.com', '1', '2014-08-06 00:00:06', 'MySpace a', 'animales'],
['b@gmail.com', '1', '2014-08-01 00:00:06', 'My Space a', 'ropa'],
['a@gmail.com', '2', '2014-08-06 00:00:06', 'My Space b', 'electronica'],
['b@gmail.com', '3', '2014-08-10 00:00:06', 'Myace c', 'animales'],
['c@gmail.com', '4', '2014-08-10 00:00:06', 'Myace c', 'animales']]
我把它分为数据和名称来处理数据:
^{pr2}$考虑到email和tel,我需要做一个包含所有重复项的字典,但是我需要应用及物性:因为如果我们考虑电子邮件,第0行=第2行,如果我们考虑tel,第1行=第3行,如果我们再次考虑电子邮件,我需要得到在这种情况下所有候选对象都是0、1、2和3,而4是单独的。在
我创建了以下代码:
from collections import defaultdict
email_to_indices = defaultdict(list)
phone_to_indices = defaultdict(list)
for idx, row in enumerate(datos):
email = row[0].lower()
phone = row[1]
email_to_indices[email].append(idx)
phone_to_indices[phone].append(idx)
所以现在我需要应用传递性规则,把0到3集合起来,单独4。在
如果你打印
print 'email', email_to_indices
print 'phone', phone_to_indices
你会得到:
email defaultdict(, {'a@gmail.com': [0, 2],'b@gmail.com': [1, 3], 'c@gmail.com': [4]})
phone defaultdict(, {'1': [0, 1], '3': [3], '2': [2], '4': [4]})
不知道如何得到考虑传递性的并集。 我需要一些类似的东西:
first_group: [0, 1, 2 , 3]
second_group: [4]
谢谢!在
这是另一种方法:
在构建}到行映射的索引。在
email_to_indices
字典时,可以将该行的电话号码存储为值,然后让phone_to_indices
拥有该行的索引。这样我们就可以创建一个email_to_indices
到{通过修改和基本的设置操作,我可以得到您想要的东西:
这样可以得到:
^{pr2}$这里有一个图形,或者更精确地说是Bipartite graph。节点有两种类型:电子邮件和电话。如果存在与该电子邮件和电话有关的记录,则会连接两个节点。或者我们甚至可以说,记录本身就是连接两个节点的边。在
任务是找到这个图的Connected components。通过以下链接,你可以找到可以在线性时间内完成的算法。在
当然,也可以发明一些快速而肮脏的解决方案,如果数据集足够小,甚至可能被认为是合适的。在
您可以在这里找到一些Python实现:Python connected components
更新:下面是一个如何构造图形的示例:
所以每个节点都有一个类型(
EMAIL
或PHONE
,它们实际上可以是整数,例如0和1,我将它们设为字符串只是为了方便打印)和一个值。Graph是一个字典,节点作为键,连接的节点集作为值。在相关问题 更多 >
编程相关推荐