简体   繁体   English

枚举python中字典键的2种组合

[英]Enumerating 2 combinations of dictionary keys in python

I wish to enumerate over all 2 combinations of dictionary keys in python. 我希望列举python中字典键的所有2种组合。 For example if I have some dictionary like: 例如,如果我有一些字典,例如:

di = {'a': [1, 2 ,5], 'b': "haha", 'c': 34, 'd': 24}

Now, suppose each key were indexed by its order. 现在,假设每个键均按其顺序索引。 For example a would be 1 b would be 2 and so forth. 例如a将为1 b将为2 ,依此类推。

Then we could do the familiar iteration to get all 2-combinations: 然后,我们可以进行熟悉的迭代以获得所有2个组合:

for i in range(len(di)):
    for j in range(i+1, len(di)):

However, the dictionary keys are not indexed as above. 但是,字典键没有如上索引。 So how do I perform this iteration? 那么如何执行此迭代?

itertools.combinations可能会有帮助。

As long as you don't want special handling to split up that list keyed to 'a': 只要您不希望特殊处理将键为'a'的列表拆分开:

list(itertools.combinations(di.values(),2))
Out[6]: 
[([1, 2, 5], 34),
 ([1, 2, 5], 'haha'),
 ([1, 2, 5], 24),
 (34, 'haha'),
 (34, 24),
 ('haha', 24)]

(python 3 syntax) (python 3语法)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM