📜  Python全组合字典列表

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

Python全组合字典列表

给定 2 个列表,形成所有可能的字典组合,这些组合可以通过从 list1 中获取键和从 list2 中获取值来形成。

方法 #1:使用 product() + 字典推导 + 列表推导

在这里,我们使用 product() 获得所有可能的组合,并且字典理解生成每个字典,列表理解用于迭代生成的组合。

Python3
# Python3 code to demonstrate working of 
# All combination Dictionary List
# Using product() + list comprehension + dictionary comprehension
from itertools import product
  
# initializing lists
test_list1 = ["Gfg", "is", "Best"]
test_list2 = [4, 5]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# generating combinations
temp = product(test_list2, repeat = len(test_list1))
  
# constructing dicts using combinations
res = [{key : val for (key , val) in zip(test_list1, ele)} for ele in temp]
  
# printing result 
print("The combinations dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of
# All combination Dictionary List
# Using product() + list comprehension + dictionary comprehension
from itertools import permutations
  
# initializing lists
test_list1 = ["Gfg", "is", "Best"]
test_list2 = [4, 5, 6]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# generating combinations
temp = list(permutations(test_list2, len(test_list1)))
  
# constructing dicts using combinations
res = [{key: val for (key, val) in zip(test_list1, ele)} for ele in temp]
  
# printing result
print("The combinations dictionary : " + str(res))


输出:

方法 #2:使用 permutations() + 字典推导 + 列表推导 [对于唯一元素]

如果我们要求值都是唯一的,可以使用 permutations() 代替 product() 来完成此任务。

蟒蛇3

# Python3 code to demonstrate working of
# All combination Dictionary List
# Using product() + list comprehension + dictionary comprehension
from itertools import permutations
  
# initializing lists
test_list1 = ["Gfg", "is", "Best"]
test_list2 = [4, 5, 6]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# generating combinations
temp = list(permutations(test_list2, len(test_list1)))
  
# constructing dicts using combinations
res = [{key: val for (key, val) in zip(test_list1, ele)} for ele in temp]
  
# printing result
print("The combinations dictionary : " + str(res))

输出: