根据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 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短