Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python – จัดกลุ่มสมาชิกในเมทริกซ์

เมื่อต้องการจัดกลุ่มสมาชิกในเมทริกซ์ (ลิสต์ของลิสต์) ตามลิสต์ตรวจสอบ สามารถใช้ลูป iteration, pop(), list comprehension และ append() ได้

ตัวอย่าง

my_list = [[14, 62], [51, 23], [12, 62], [78, 87], [41, 14]]
print("The list is :")
print(my_list)
check_list = [14, 12, 41, 62]
print("The list is :")
print(check_list)
my_result = []
while my_list:
    sub_list_1 = my_list.pop()
    sub_list_2 = [element for element in check_list if element not in sub_list_1]
    try:
        my_list.remove(sub_list_2)
        my_result.append([sub_list_1, sub_list_2])
    except ValueError:
        my_result.append(sub_list_1)
print("The result is :")
print(my_result)

ผลลัพธ์

The list is : [[14, 62], [51, 23], [12, 62], [78, 87], [41, 14]]
The list is : [14, 12, 41, 62]
The result is : [[[41, 14], [12, 62]], [78, 87], [51, 23], [14, 62]]

คำอธิบาย

  • กำหนดเมทริกซ์ (ลิสต์ของลิสต์) และลิสต์ตรวจสอบ (check_list)

  • ใช้ลูป while ดึงสับลิสต์ท้ายสุดออกด้วย pop()

  • หาสมาชิกใน check_list ที่ไม่อยู่ใน sub_list_1 ด้วย list comprehension

  • ลองลบ sub_list_2 ออกจาก my_list ที่เหลือ ถ้าสำเร็จ จับคู่ทั้งสอง ถ้าไม่สำเร็จ (ValueError) เก็บแค่ sub_list_1

  • แสดงผลลัพธ์การจัดกลุ่ม