เมื่อต้องการเรียงลำดับเมทริกซ์สตริงตามจำนวนตัวอักษรทั้งหมด (total characters) ในแต่ละแถว สามารถใช้ฟังก์ชันช่วยที่มี list comprehension, sum() และ len() ได้
ตัวอย่าง
def total_characters(row):
return sum([len(element) for element in row])
my_list = [["pyt", "is", "fun"], ["python", "fun"], ["py", "4", "good"], ["python"]]
print("The list is :")
print(my_list)
my_list.sort(key=total_characters)
print("The result is :")
print(my_list)
ผลลัพธ์
The list is : [['pyt', 'is', 'fun'], ['python', 'fun'], ['py', '4', 'good'], ['python']] The result is : [['python'], ['py', '4', 'good'], ['pyt', 'is', 'fun'], ['python', 'fun']]
คำอธิบาย
กำหนดฟังก์ชัน
total_charactersคำนวณlen()ของแต่ละสตริงในแถว รวมด้วยsum()กำหนดเมทริกซ์สตริงและแสดงผล
ใช้
sort(key=total_characters)เรียงตามจำนวนตัวอักษรรวมจากน้อยไปมากจำนวนตัวอักษร: ['python']=6, ['py','4','good']=7, ['pyt','is','fun']=8, ['python','fun']=9