📜  Python – 按 K字符频率排序字符串列表

📅  最后修改于: 2022-05-13 01:55:46.801000             🧑  作者: Mango

Python – 按 K字符频率排序字符串列表

给定字符串列表,根据特定字符的频率进行排序操作。

方法 #1:使用 sorted() + count() + lambda

在此,sorted() 用于执行排序任务,count() 是要执行排序的函数。使用额外的关键参数,并且使用的函数封装是 lambda。

Python3
# Python3 code to demonstrate working of
# Sort String list by K character frequency
# Using sorted() + count() + lambda
 
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 'e'
 
# "-" sign used to reverse sort
res = sorted(test_list, key = lambda ele: -ele.count(K))
 
# printing results
print("Sorted String : " + str(res))


Python3
# Python3 code to demonstrate working of
# Sort String list by K character frequency
# Using sort() + count() + lambda
 
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 'e'
 
# "-" sign used to reverse sort
# inplace sort
test_list.sort(key = lambda ele: -ele.count(K))
 
# printing results
print("Sorted String : " + str(test_list))


输出
The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
Sorted String : ['geekforgeeks', 'geeks', 'best', 'is', 'for']

方法 #2:使用 sort() + count() + lambda

在这里,我们使用 sort() 执行排序任务,这与上面类似,唯一的区别是排序是就地完成的。

Python3

# Python3 code to demonstrate working of
# Sort String list by K character frequency
# Using sort() + count() + lambda
 
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 'e'
 
# "-" sign used to reverse sort
# inplace sort
test_list.sort(key = lambda ele: -ele.count(K))
 
# printing results
print("Sorted String : " + str(test_list))
输出
The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
Sorted String : ['geekforgeeks', 'geeks', 'best', 'is', 'for']