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

Python – กรองแถวที่มีสมาชิกตามที่ต้องการ

เมื่อต้องการกรองแถวที่มีสมาชิกทุกตัวอยู่ในลิสต์ที่กำหนด (check_list) สามารถใช้ list comprehension และ all() ได้

ตัวอย่าง

my_list = [[261, 49, 61], [27, 49, 3, 261], [261, 49, 85], [1, 1, 9]]
print("The list is :")
print(my_list)
check_list = [49, 61, 261, 85]
my_result = [index for index in my_list if all(element in check_list for element in index)]
print("The result is :")
print(my_result)

ผลลัพธ์

The list is : [[261, 49, 61], [27, 49, 3, 261], [261, 49, 85], [1, 1, 9]]
The result is : [[261, 49, 61], [261, 49, 85]]

คำอธิบาย

  • กำหนดเมทริกซ์และลิสต์ค่าที่อนุญาต (check_list)

  • ใช้ list comprehension วนลูปแต่ละแถว (index)

  • ใช้ all(element in check_list for element in index) ตรวจสอบว่าสมาชิกทุกตัวในแถวอยู่ใน check_list

  • เก็บเฉพาะแถวที่ผ่านเงื่อนไข แสดงผลลัพธ์