根据元素长度对 Python 程序中的列表进行排序
我们有一个字符串列表,我们的目标是根据列表中字符串的长度对列表进行排序。我们必须根据字符串的长度按升序排列字符串。我们可以使用我们的算法或Python内置方法sort()或函数sorted()以及一个键来实现这一点。
让我们举个例子来看看输出。
Input: strings = ["hafeez", "aslan", "honey", "appi"] Output: ["appi", "aslan", "honey", "hafeez"]
让我们使用sort(key)和sorted(key)编写我们的程序。按照以下步骤使用sorted(key)函数获得所需的输出。
算法
1. Initialize the list of strings. 2. Sort the list by passing list and key to the sorted(list, key = len) function. We have to pass len as key for the sorted() function as we are sorting the list based on the length of the string. Store the resultant list in a variable. 3. Print the sorted list.
示例
## initializing the list of strings strings = ["hafeez", "aslan", "honey", "appi"] ## using sorted(key) function along with the key len sorted_list = list(sorted(strings, key = len)) ## printing the strings after sorting print(sorted_list)
输出
如果运行以上程序,将得到以下输出。
['appi', 'aslan', 'honey', 'hafeez']
算法
1. Initialize the list of strings. 2. Sort the list by passing key to the sort(key = len) method of the list. We have to pass len as key for the sort() method as we are sorting the list based on the length of the string. sort() method will sort the list in place. So, we don't need to store it in new variable. 3. Print the list.
示例
## initializing the list of strings strings = ["hafeez", "aslan", "honey", "appi"] ## using sort(key) method to sort the list in place strings.sort(key = len) ## printing the strings after sorting print(strings)
输出
如果运行以上程序,将得到以下输出。
['appi', 'aslan', 'honey', 'hafeez']
结论
如果您对本教程有任何疑问,请在评论区提出。
广告