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

Python – เรียงลำดับเมทริกซ์ตามความยาวสตริงสูงสุดในแถว

เมื่อต้องการเรียงลำดับเมทริกซ์สตริงตามความยาวสตริงสูงสุด (maximum string length) ในแต่ละแถว สามารถใช้ฟังก์ชันช่วยที่มี list comprehension, max() และ len() ได้

ตัวอย่าง

def max_length(row):
    return max([len(element) for element in row])

my_matrix = [['pyt', 'fun'], ['python'], ['py', 'cool'], ['py', 'ea']]
print("The matrix is :")
print(my_matrix)
my_matrix.sort(key=max_length)
print("The result is :")
print(my_matrix)

ผลลัพธ์

The matrix is : [['pyt', 'fun'], ['python'], ['py', 'cool'], ['py', 'ea']]
The result is : [['py', 'ea'], ['pyt', 'fun'], ['py', 'cool'], ['python']]

คำอธิบาย

  • กำหนดฟังก์ชัน max_length คำนวณความยาวของแต่ละสตริงในแถว หาค่า max()

  • กำหนดเมทริกซ์สตริงและแสดงผล

  • ใช้ sort(key=max_length) เรียงตามความยาวสูงสุดในแถวจากน้อยไปมาก

  • ความยาวสูงสุดต่อแถว: ['pyt','fun']=3, ['python']=6, ['py','cool']=4, ['py','ea']=2 -> เรียงได้ผลลัพธ์