根据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']
结论
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短