📜  Python|组合列表字典中的值

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

Python|组合列表字典中的值

给定一个列表值字典,任务是在每个组合中组合每个键值对。

方法 #1:使用 itertools 和排序

# Python code to combine every key value
# pair in every combinations
  
# List initialization
Input = {
"Bool" : ["True", "False"],
"Data" : ["Int", "Float", "Long Long"],
}
  
# Importing
import itertools as it
  
# Sorting input
sorted_Input = sorted(Input)
  
# Using product after sorting
Output = [dict(zip(sorted_Input, prod)) 
          for prod in it.product(*(Input[sorted_Input]
          for sorted_Input in sorted_Input))]
  
# Printing output
print(Output)
输出:


方法 #2:使用 Zip

# Python code to combine every key value
# pair in every combinations
  
# Importing
import itertools
  
# Input Initialization
Input = {
"Bool" : ["True", "False"],
"Data" : ["Int", "Float", "Long Long"],
}
  
# using zip and product without sorting
Output = [[{key: value} for (key, value) in zip(Input, values)] 
              for values in itertools.product(*Input.values())]
                  
# Printing output
print(Output)
输出: