Python – 字典列表的所有组合
pythonserver side programmingprogramming更新于 2025/10/14 15:40:17
当需要显示字典列表的所有组合时,可以使用简单的列表推导和‘zip’方法以及‘product’方法。
下面是相同的演示 −
示例
from itertools import product
my_list_1 = ["python", "is", "fun"]
my_list_2 = [24, 15]
print("第一个列表是:")
print(my_list_1)
print("第二个列表是:")
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("结果为:")
print(my_result)
输出
第一个列表是:
['python', 'is', 'fun']
第二个列表是:
[24, 15]
结果为:
[{'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’方法计算两个列表的笛卡尔积。
此结果分配给一个变量。
使用列表推导式对列表进行迭代,并使用第一个列表的元素和先前定义的变量的元素创建字典。
这被分配给一个变量。
这是控制台上显示的输出。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

