ใช้ sorted() ร่วมกับ lambda คำนวณจำนวนหลักตัวเลขรวมในแต่ละ Tuple แล้วจัดเรียง
ตัวอย่างโค้ด
my_list = [(11, 23, 45, 678), (34, 67), (653,), (78, 99, 23, 45), (67, 43)]
print("The list is : ")
print(my_list)
my_result = sorted(my_list, key=lambda tup: sum([len(str(ele)) for ele in tup]))
print("The sorted tuples are ")
print(my_result)
ผลลัพธ์
The list is : [(11, 23, 45, 678), (34, 67), (653,), (78, 99, 23, 45), (67, 43)] The sorted tuples are [(653,), (34, 67), (67, 43), (78, 99, 23, 45), (11, 23, 45, 678)]
คำอธิบาย
- กำหนด List of Tuples
- Lambda function: แปลงแต่ละสมาชิกเป็นสตริง หาความยาว รวมกัน
- sorted() ใช้ key นี้จัดเรียงจากน้อยไปมาก