ภาพรวม
จาก list หลักขนาด k และ replacement list ให้สร้าง combination ทุกแบบของขนาด k โดยเลือกจาก pool รวม (หลัก + replacement)
ตัวอย่างโค้ด
from itertools import combinations
my_list = [54, 98, 11]
replace_list = [8, 10]
# รวม list แล้วหา combinations ขนาดเท่าเดิม (3)
my_result = list(combinations(my_list + replace_list, len(my_list)))
print("The list is:", my_list)
print("Replace list:", replace_list)
print("The result is:", my_result)
ผลลัพธ์
The list is: [54, 98, 11]
Replace list: [8, 10]
The result is:
[(54, 98, 11), (54, 98, 8), (54, 98, 10), (54, 11, 8), (54, 11, 10),
(54, 8, 10), (98, 11, 8), (98, 11, 10), (98, 8, 10), (11, 8, 10)]
คำอธิบาย
- Pool รวม = [54, 98, 11, 8, 10] (5 elements)
- หา combinations ขนาด 3 (เท่ากับ len(my_list))
- C(5,3) = 10 combinations
- ตัวแรก (54, 98, 11) คือ combination เดิม ไม่มี replacement
กรณีต้องการแทนที่จริง (Replace specific positions)
# หากต้องการแทนที่ element ที่ index 1 (98) ด้วยค่าจาก replace_list
import itertools
original = [54, 98, 11]
replacements = [8, 10]
index_to_replace = 1
results = []
for r in replacements:
new = original.copy()
new[index_to_replace] = r
results.append(tuple(new))
print(results) # [(54, 8, 11), (54, 10, 11)]