如果有字典:
test_dict = { 'a':1,'b':2,'c':3,'d':4}
我想在元组列表中找到键对,例如:
[('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') 是相似的,我只希望其中之一出现在列表中。我不得不再运行一个循环以从结果中获取唯一对。
那么在 Python 中(最好是在 2.x 中)有什么有效的方法吗?我想删除嵌套循环。
更新:
我已经检查了可能的 flagged duplicate ,但这并没有解决这里的问题。它只是提供不同的组合。我只需要 2 对。对于这个问题,('a','b','c') 和 ('a','b','c' ,'d') 是有效的,但对我来说它们不是。我希望这可以解释差异。
请您参考如下方法:
听起来像是 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')]
我应该补充一点,虽然上面的输出恰好是排序的,但这并不能保证。如果顺序很重要,您可以改用:
results = sorted(combinations(test_dict, 2))
