เมื่อต้องการสร้างคู่สั่ง (ordered pairs) ทั้งหมดจากช่วงตัวเลข 1 ถึง N สามารถใช้ itertools.product กับพารามิเตอร์ repeat=N
ตัวอย่างโค้ด
from itertools import product
N = 2
print("The value of N is:", N)
result = [ele for ele in product(range(1, N + 1), repeat=N)]
print("All tuple combinations up to", N, "are:")
print(result)ผลลัพธ์
The value of N is: 2 All tuple combinations up to 2 are: [(1, 1), (1, 2), (2, 1), (2, 2)]
คำอธิบาย
นำเข้า
productจากitertoolsสำหรับ Cartesian productrange(1, N+1)สร้างลำดับ 1 ถึง Nrepeat=Nหมายถึงเลือก N ครั้ง (สร้าง N-tuples)ผลลัพธ์คือทุกค่าสามารถเป็นของ N-tuples จากเซ็ต {1, 2, ..., N}