查找字典的所有唯一键对 [英] Find all unique pairs of keys of a dictionary

查看:46
本文介绍了查找字典的所有唯一键对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有字典:

test_dict = { 'a':1,'b':2,'c':3,'d':4}

我想在元组列表中找到一对密钥:

I want to find pairs of keys in list of tuples like:

[('a','b'),('a','c'),('a','d'),('b','c'),('b','d'),('c','d')]

我尝试了以下两次迭代

test_dict = { 'a':1,'b':2,'c':3,'d':4}
result = []
for first_key in test_dict:
    for second_key in test_dict:
        if first_key != second_key:
            pair = (first_key,second_key)
            result.append(pair)

但是它产生了以下结果

[('a', 'c'), ('a', 'b'), ('a', 'd'), ('c', 'a'), ('c', 'b'), ('c', 'd'), ('b', 'a'), ('b', 'c'), ('b', 'd'), ('d', 'a'), ('d', 'c'), ('d', 'b')]

对于我的测试用例('a','b')和('b','a')是相似的,我只希望它们在列表中.我必须再运行一个循环才能从结果中获得唯一对.

For my test case ('a','b') and ('b','a') are similar and I just want one of them in the list. I had to run one more loop for getting the unique pairs from the result.

那么在Python中(最好是在2.x中)有什么有效的方法吗?我想删除嵌套循环.

So is there any efficient way to do it in Python (preferably in 2.x)? I want to remove nested loops.

更新:
我已经检查了可能的已标记重复项,但是这里并没有解决问题.它只是提供不同的组合.我只需要2对.对于这个问题,('a','b','c')('a','b','c','d')有效,但对我而言无效.我希望,这可以解释差异.

Update:
I have checked with the possible flagged duplicate, but it's not solving the problem here. It's just providing different combination. I just need the pairs of 2. For that question a tuple of ('a','b','c') and ('a','b','c','d') are valid, but for me they are not. I hope, this explains the difference.

推荐答案

听起来像 itertools .

from itertools import combinations
test_dict = {'a':1, 'b':2, 'c':3, 'd':4}
results = list(combinations(test_dict, 2))

[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

我应该补充一点,尽管上面的输出恰好是排序的,但不能保证.如果顺序很重要,则可以使用:

I should add that although the output above happens to be sorted, this is not guaranteed. If order is important, you can instead use:

results = sorted(combinations(test_dict, 2))

这篇关于查找字典的所有唯一键对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆