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

Python – เรียงแถวของเมทริกซ์ตามจำนวนสมาชิกที่กำหนดเอง


เมื่อต้องการเรียงแถวของเมทริกซ์ตามจำนวนสมาชิกที่กำหนดเอง จะนิยามฟังก์ชันที่ใช้ List Comprehension และเมธอด len() เพื่อหาผลลัพธ์

ตัวอย่าง

def get_count_matrix(my_key):
    return len([element for element in my_key if element in custom_list])

my_list = [[31, 5, 22, 7], [85, 5], [9, 11, 22], [7, 48]]
print("The list is :")
print(my_list)
custom_list = [31, 85, 7]
my_list.sort(key=get_count_matrix)
print("The resultant list is :")
print(my_list)

ผลลัพธ์

The list is : [[31, 5, 22, 7], [85, 5], [9, 11, 22], [7, 48]]
The resultant list is : [[9, 11, 22], [85, 5], [7, 48], [31, 5, 22, 7]]

คำอธิบาย

  • นิยามฟังก์ชัน get_count_matrix ที่รับ key เป็นพารามิเตอร์

  • ใช้ List Comprehension วนลูปตรวจสอบว่าสมาชิกอยู่ใน custom_list หรือไม่

  • คืนค่าจำนวนสมาชิกที่ตรงกับ custom_list

  • นอกจากฟังก์ชัน กำหนดรายการของรายการและแสดงผล

  • กำหนด custom_list

  • เรียงลำดับรายการด้วย sort() โดยระบุ key เป็นฟังก์ชันที่นิยามไว้

  • แสดงผลลัพธ์บนคอนโซล