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”方法計算兩個列表的笛卡爾積。

  • 此結果被分配給一個變數。

  • 列表解析用於迭代此列表,並且第一個列表的元素和先前定義變數的元素用於建立一個字典。

  • 分配給一個變數。

  • 這是顯示在控制檯上的輸出。

更新於: 2021-09-06

809 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.