python - 在 python 字典或数据框中查找共现

标签 python dictionary pandas

我有两个字典(如果需要,可以轻松转换为数据帧),我想找到其中名称的共现( friend )。第一个字典包含名称之间的关系。

我的字典:

{'George': ['Bill','Mary'],
'Bill': ['George'],
'Sam' : [],
....}

另一本字典包含一起出去的人的列表

我的_dict2:

{1: 'Mary,George,Sandra,Alice',
 2: 'Bob,Bill,Sam,George',
 3: 'Simon,Frank',
 ....}

我想找到一起出去的 friend 的列表/字典/数据框。所以预期的输出是:

Mary,George
Bill,George
..

我试过了

for key, my_dict_values in my_dict.items():
    for my_dict2_values in my_dict2.values():
        if key == my_dict2_values and my_dict_values == my_dict2_values :
        ....

但是它不起作用,并且需要很长时间才能给出结果。有什么建议吗?

谢谢

最佳答案

这段代码非常慢(O(n^3)),因此请考虑优化您的数据结构,看看是否可以改进访问好友详细信息的方式。

d1 = {'George': ['Bill','Mary'],
'Bill': ['George'],
'Sam' : [],
}

d2 = {1: 'Mary,George,Sandra,Alice',
 2: 'Bob,Bill,Sam,George',
 3: 'Simon,Frank',
 }

out = []
for p1, friends in d1.items():
    for friend in friends:
        for party in d2.values():
            if p1 in party and friend in party:
                out.append([p1,friend])

print out

给予:

[['Bill', 'George'], ['George', 'Bill'], ['George', 'Mary']]

其次,尝试编写真正描述您正在做的事情的代码,因为这样更容易理解。例如,考虑:

for key, my_dict_values in my_dict.items():
    for my_dict2_values in my_dict2.values():
        if key == my_dict2_values and my_dict_values == my_dict2_values :

比较:

for p1, friends in d1.items():
    for friend in friends:
        for party in d2.values():
            if p1 in party and friend in party:

关于python - 在 python 字典或数据框中查找共现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33726061/

相关文章:

python - 可变数量的前导零

python - 访问值列表中的特定值

python - 以编程方式轻轻更改哈希

python - 在 Q# 中获取数字序列

Python在修改输出后保留缩进

python - 排序二维列表python

python - 选择大于 panda 数据框中数字的所有值

c# - 在 C# 中打印字典键值对

python - Pandas:如何将字典映射到 2 列?

python - 在pandas和matplotlib中,为什么不直接在数据帧上调用plt?