Python——按符號頻率對字串列表進行排序
必須基於“K”的字數字符串頻率、`sorted` 方法和 lambda 函式對字串列表進行排序時,將使用
示例
以下是一個演示 −
my_list = ['Hi', 'Will', 'Jack', 'Python', 'Bill', 'Mills', 'goodwill']
print("The list is : " )
print(my_list)
my_list.sort()
print("The list after sorting is ")
print(my_list)
K = 'l'
print("The value of K is ")
print(K)
my_result = sorted(my_list, key = lambda ele: -ele.count(K))
print("The resultant list is : ")
print(my_result)輸出
The list is : ['Hi', 'Will', 'Jack', 'Python', 'Bill', 'Mills', 'goodwill'] The list after sorting is ['Bill', 'Hi', 'Jack', 'Mills', 'Python', 'Will', 'goodwill'] The value of K is l The resultant list is : ['Bill', 'Mills', 'Will', 'goodwill', 'Hi', 'Jack', 'Python']
說明
定義了一個字串列表,並在控制檯上顯示。
對列表以升序進行排列,並在控制檯上顯示。
`K` 的值已初始化並顯示在控制檯上。
使用 sorted 方法對列表進行排序,將鍵指定為 lambda 函式。
這將分配給一個在控制檯上顯示的變數。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP