根据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']
结论
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿