Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình Python sắp xếp List theo độ dài phần tử


Dùng một list nhập từ người dùng, sắp xếp list theo độ dài các phần tử. Dùng built-in sorted().

Ví dụ

Input: ["mona", "pp", "aaa"]
Lengths: [4, 2, 3]
Sorted array: [2, 3, 4]
Output: ["pp", "aaa", "mona"]

Thuật toán

Bước 1: Nhập phần tử list.
Bước 2: Áp dụng sorted(A, key=len).

Ví dụ mã

# Sắp xếp list theo độ dài phần tử
def sortedlist(A):
    newlist = sorted(A, key=len)
    return newlist

# Driver code
A = list()
n = int(input("Enter the size of the List ::"))
print("Enter the Element ::")
for i in range(int(n)):
    k = input("")
    A.append(k)
print("SORTED LIST ::>", sortedlist(A))

Kết quả

Enter the size of the List ::5
Enter the Element ::
mona
gulli
adwaita
aadrika
pinki
SORTED LIST ::> ['mona', 'gulli', 'pinki', 'adwaita', 'aadrika']