📜  Python – 字典键值列表组合

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

Python – 字典键值列表组合

给定具有值作为列表的字典,提取所有可能的组合,包括交叉键和值。

方法 #1:使用 product() + zip() + loop

上述功能的组合可以用来解决这个问题。在此,我们使用 product() 执行所有值的第一个键组合,并使用 zip() 和循环执行交叉键组合。

Python3
# Python3 code to demonstrate working of 
# Dictionary Key Value lists combinations
# Using product() + zip() + loop
from itertools import product
  
# initializing dictionary
test_dict = {"Gfg" : [4, 5, 7],
             "is" : [1, 2, 9],
             "Best" : [9, 4, 2]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
temp = list(test_dict.keys())        
res = dict()
cnt = 0
  
# making key-value combinations using product
for combs in product (*test_dict.values()):
       
    # zip used to perform cross keys combinations.
    res[cnt] = [[ele, cnt] for ele, cnt in zip(test_dict, combs)]
    cnt += 1
  
# printing result 
print("The computed combinations : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Dictionary Key Value lists combinations
# Using product() + loop
from itertools import product
  
# initializing dictionary
test_dict = {"Gfg" : [4, 5, 7],
             "is" : [1, 2, 9],
             "Best" : [9, 4, 2]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
res = {}
for key, val in test_dict.items():
      
    # for key-value combinations 
    res[key] = product([key], val)
  
# computing cross key combinations
res = product(*res.values())
  
# printing result 
print("The computed combinations : " + str(list(res)))


输出

方法 #2:使用 product() + 循环

上述功能的组合也可以用来解决这个问题。在此,我们使用 product() 执行执行内部和交叉键组合的任务。不同之处在于分组容器是元组而不是列表。

Python3

# Python3 code to demonstrate working of 
# Dictionary Key Value lists combinations
# Using product() + loop
from itertools import product
  
# initializing dictionary
test_dict = {"Gfg" : [4, 5, 7],
             "is" : [1, 2, 9],
             "Best" : [9, 4, 2]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
res = {}
for key, val in test_dict.items():
      
    # for key-value combinations 
    res[key] = product([key], val)
  
# computing cross key combinations
res = product(*res.values())
  
# printing result 
print("The computed combinations : " + str(list(res))) 
输出