เมื่อจำเป็นต้องค้นหาชุดค่าผสมทั้งหมดในรายการที่มีเงื่อนไขที่กำหนด ระบบจะใช้การวนซ้ำแบบง่าย วิธีการผนวก และวิธีการ 'อินสแตนซ์' จะถูกนำมาใช้
ตัวอย่าง
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
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 ถูกกำหนดและแสดงบนคอนโซล
-
มีการสร้างรายการที่ว่างเปล่า
-
ตัวแปร 'นับ' ถูกสร้างขึ้นและถูกกำหนดให้เป็น 0
-
วง while ใช้เพื่อวนซ้ำรายการ และวิธีการ 'isinstance' ใช้เพื่อตรวจสอบว่าประเภทขององค์ประกอบตรงกับประเภทเฉพาะหรือไม่
-
ขึ้นอยู่กับสิ่งนี้ องค์ประกอบจะถูกผนวกเข้ากับรายการที่ว่างเปล่า
-
นี่คือเอาต์พุตที่แสดงบนคอนโซล