Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python – Tất cả tổ hợp của danh sách từ điển


Khi cần tạo tất cả các tổ hợp của danh sách từ điển (tích Descartes), ta dùng itertools.product, zip và list comprehension.

Ví dụ

from itertools import product

my_list_1 = ["python", "is", "fun"]
my_list_2 = [24, 15]
print("Danh sách đầu tiên:")
print(my_list_1)
print("Danh sách thứ hai:")
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("Kết quả:")
print(my_result)

Kết quả

Danh sách đầu tiên: ['python', 'is', 'fun']
Danh sách thứ hai: [24, 15]
Kết quả: [{'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}]

Giải thích

  • Nhập product từ itertools.

  • Hai danh sách: keys (chuỗi) và values (số).

  • product(my_list_2, repeat=len(my_list_1)) tạo ra tất cả các tuple độ dài 3 từ các giá trị của list_2.

  • List comprehension: với mỗi tuple, dùng zip ghép với list_1 tạo từ điển.

  • In danh sách các từ điển kết quả.