查找字典的所有唯一键对

编程入门 行业动态 更新时间:2024-10-10 00:25:44
本文介绍了查找字典的所有唯一键对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果有字典:

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))

更多推荐

查找字典的所有唯一键对

本文发布于:2023-10-19 02:00:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1506060.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:一键   字典

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!