Python - 字典列表的所有组合
当要求列出字典列表的所有组合时,会用到简单的列表解析和“zip”方法以及“product”方法。
以下是演示代码示例 −
示例
from itertools import product
my_list_1 = ["python", "is", "fun"]
my_list_2 = [24, 15]
print("The first list is :")
print(my_list_1)
print("The second list is :")
print(my_list_2)
temp = product(my_list_2, repeat = len(my_list_1))
my_result = [{key : value for (key , value) in zip(my_list_1, element)} for element in temp]
print("The result is :")
print(my_result)输出
The first list is :
['python', 'is', 'fun']
The second list is :
[24, 15]
The result is :
[{'python': 24, 'is': 24, 'fun': 24}, {'python': 24, 'is': 24, 'fun': 15}, {'python': 24, 'is': 15, 'fun': 24}, {'python': 24, 'is': 15, 'fun': 15}, {'python': 15, 'is': 24, 'fun': 24}, {'python': 15, 'is': 24, 'fun': 15}, {'python': 15, 'is': 15, 'fun': 24}, {'python': 15, 'is': 15, 'fun': 15}]说明
所需的包已导入到环境中。
定义了两个列表并显示在控制台上。
使用“product”方法计算两个列表的笛卡尔积。
此结果被分配给一个变量。
列表解析用于迭代此列表,并且第一个列表的元素和先前定义变量的元素用于创建一个字典。
分配给一个变量。
这是显示在控制台上的输出。
广告
数据结构
网络
关系型数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP