根據元素長度對 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']
結論
如果您對本教程有任何疑問,請在評論區提出。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP