# Python根据元素的长度对列表进行排序

Input : list = ["rohan", "amy", "sapna", "muhammad", "aakash", "raunak", "chinmoy"]
Output : ['amy', 'rohan', 'sapna', 'aakash', 'raunak', 'chinmoy', 'muhammad']

Input : list = [["ram", "mohan", "aman"], ["gaurav"], ["amy", "sima", "ankita", "rinku"]]
Output : [['gaurav'], ['ram', 'mohan', 'aman'], ['amy', 'sima', 'ankita', 'rinku']]

Note: The first example comprises of Strings whose
length can be calculated. The second example comprises
of sublists, which is also arranged according to there
length.

sorted_list = sorted(unsorted_list, key=len)
# Python code to sort a list by creating
# another list Use of sorted()
def Sorting(lst):
lst2 = sorted (lst, key = len )
return lst2

# Driver code
lst = [ "rohan" , "amy" , "sapna" , "muhammad" , "aakash" , "raunak" , "chinmoy" ]
print (Sorting(lst))

unsorted_list.sort(key=len)
# Python code to sort a list without
# creating another list Use of sort()
def Sorting(lst):
lst.sort(key = len )
return lst

# Driver code
lst = [ "rohan" , "amy" , "sapna" , "muhammad" , "aakash" , "raunak" , "chinmoy" ]
print (Sorting(lst))

['amy', 'rohan', 'sapna', 'aakash', 'raunak', 'chinmoy', 'muhammad']

Python在排序时实现的这些关键功能称为装饰-排序-无法装饰的设计模式。它遵循以下步骤：

1. 列表中的每个元素都将临时替换为”装饰”版本, 其中包括应用于该元素的键函数的结果。
2. 该列表根据键的自然顺序排序。
3. 装饰元素将替换为原始元素。

import numpy

def Sorting(lst):

# list for storing the length of each string in list
lenlist = []
for x in lst:
lenlist.append( len (x))

# return a list with the index of the sorted
# items in the list
sortedindex = numpy.argsort(lenlist)

# creating a dummy list where we will place the
# word according to the sortedindex list
lst2 = [ 'dummy' ] * len (lst)

# print(sortedindex, lenlist)
for i in range ( len (lst)):

# placing element in the lst2 list by taking the
# value from original list lst where it should belong
# in the sorted list by taking its index from sortedindex
lst2[i] = lst[sortedindex[i]]

return lst2

# Driver code
lst = [ "rohan" , "amy" , "sapna" , "muhammad" , "aakash" , "raunak" , "chinmoy" ]
print (Sorting(lst))

['amy', 'rohan', 'sapna', 'aakash', 'raunak', 'chinmoy', 'muhammad']

• 回顶