เมื่อต้องการหาการจัดหมู่ (combinations) ทั้งหมดในลิสต์ที่มีโครงสร้างผสมตามเงื่อนไข สามารถใช้ลูป iteration, append() และ isinstance() ได้
ตัวอย่าง
my_list = ["python", [15, 12, 33, 14], "is", ["fun", "easy", "better", "cool"]]
print("The list is :")
print(my_list)
K = 4
print("The value of K is :")
print(K)
my_result = []
count = 0
while count <= K - 1:
temp = []
for index in my_list:
if not isinstance(index, list):
temp.append(index)
else:
temp.append(index[count])
count += 1
my_result.append(temp)
print("The result is :")
print(my_result)
ผลลัพธ์
The list is : ['python', [15, 12, 33, 14], 'is', ['fun', 'easy', 'better', 'cool']] The value of K is : 4 The result is : [['python', 15, 'is', 'fun'], ['python', 12, 'is', 'easy'], ['python', 33, 'is', 'better'], ['python', 14, 'is', 'cool']]
คำอธิบาย
กำหนดลิสต์ที่มีทั้งสตริงและลิสต์ย่อย แสดงผล
กำหนด K (จำนวนการจัดหมู่ที่ต้องการ)
ใช้ลูป while นับจาก 0 ถึง K-1 ในแต่ละรอบ สร้างลิสต์ชั่วคราว temp
วนลูปผ่าน my_list ถ้าสมาชิกไม่ใช่ลิสต์ ใส่ตรงๆ ถ้าเป็นลิสต์ ใส่สมาชิกที่ดัชนี count
เพิ่ม temp เข้า my_result แสดงผลลัพธ์การจัดหมู่ทั้งหมด