📌  相关文章
📜  Python |根据元素的长度对列表进行排序

📅  最后修改于: 2021-04-27 18:07:08             🧑  作者: Mango

在此程序中,我们需要接受一个列表,并根据其中包含的元素的长度对其进行排序。
例子:

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为我们提供了各种内置函数来执行这些算法。内置函数包括sort()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在排序时实现的这些关键函数被称为decorate-sort-undecorate设计模式。它遵循以下步骤:

  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']


参考:
stackoverflow