Python程序根据元素的长度对列表进行排序?
在这里,我们使用一个用户输入数组,并且必须根据元素的长度对列表进行排序。在这里,我们使用Python内置函数sorted()。
示例
Input::[“mona”,”pp”,”aaa”] Lengths are [4,2,3] So, the sorted array should be [2,3,4] Output::[“pp”,”aaa”,”mona”]
算法
Step 1: Input list element. Step 2: apply sorted (A,len) function.
范例程式码
# To sort a list
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))输出结果
Enter the size of the List ::5 Enter the Element :: mona gulli adwaita aadrika pinki SORTED LIST ::> ['mona', 'gulli', 'pinki', 'adwaita', 'aadrika']
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短