📜  Python|字典组合键

📅  最后修改于: 2022-05-13 01:55:03.437000             🧑  作者: Mango

Python|字典组合键

有时,在使用Python字典时,我们可能会遇到需要获取字典对的所有可能对组合的问题。这种应用可以发生在数据科学领域。让我们讨论可以执行此任务的某些方式。

方法 #1:使用列表理解 + enumerate()
在这种方法中,我们只是通过列表理解迭代字典并构造键对并插入新列表。 enumerate函数用于通过访问索引将关键元素绑定在一起。

# Python3 code to demonstrate working of
# Dictionary key combinations
# Using list comprehension + enumerate()
  
# Initializing dict
test_dict = {'gfg' : 1, 'is' : 2, 'the' : 3, 'best' : 4}
  
# printing original dict
print("The original dict is : " + str(test_dict))
  
# Dictionary key combinations
# Using list comprehension + enumerate()
test_dict = list(test_dict)
res = [(x, y) for idx, x in enumerate(test_dict) for y in test_dict[idx + 1: ]]
      
# printing result
print("The dictionary key pair list is : " + str(res))
输出 :
The original dict is : {'is': 2, 'the': 3, 'best': 4, 'gfg': 1}
The dictionary key pair list is : [('is', 'the'), ('is', 'best'), ('is', 'gfg'), ('the', 'best'), ('the', 'gfg'), ('best', 'gfg')]

方法 #2:使用itertools.combinations()
这个任务可以使用combinations()的功能来执行,它在内部只需要键来形成元素对。

# Python3 code to demonstrate working of
# Dictionary key combinations
# Using itertools.combinations()
import itertools
  
# Initializing dict
test_dict = {'gfg' : 1, 'is' : 2, 'the' : 3, 'best' : 4}
  
# printing original dict
print("The original dict is : " + str(test_dict))
  
# Dictionary key combinations
# Using itertools.combinations()
res = list(itertools.combinations(test_dict, 2))
  
# printing result
print("The dictionary key pair list is : " + str(res))
输出 :
The original dict is : {'is': 2, 'the': 3, 'best': 4, 'gfg': 1}
The dictionary key pair list is : [('is', 'the'), ('is', 'best'), ('is', 'gfg'), ('the', 'best'), ('the', 'gfg'), ('best', 'gfg')]