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.

有许多方法可以执行此操作。任何人都可以使用自己的算法技术, 但是Python为我们提供了各种内置函数来执行这些算法。内置功能包括分类()和sorted()以及key参数。我们可以通过两种方式执行这些操作。一种方法是通过创建新列表对列表进行排序, 另一种方法是在给定列表内进行排序, 以节省空间。
通过创建新列表进行排序的语法为:
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根据元素的长度对列表进行排序】加工:
Python在排序时实现的这些关键功能称为装饰-排序-无法装饰的设计模式。它遵循以下步骤:
  1. 列表中的每个元素都将临时替换为” 装饰” 版本, 其中包括应用于该元素的键函数的结果。
  2. 该列表根据键的自然顺序排序。
  3. 装饰元素将替换为原始元素。
通过创建新的虚拟列表进行排序的代码为:
import numpydef 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']

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。

    推荐阅读