Python – 按 K字符频率排序字符串列表
给定字符串列表,根据特定字符的频率进行排序操作。
Input : test_list = [“geekforgeekss”, “is”, “bessst”, “for”, “geeks”], K = ‘s’
Output : [‘bessst’, ‘geekforgeekss’, ‘geeks’, ‘is’, ‘for’]
Explanation : bessst has 3 occurrence, geeksforgeekss has 3, and so on.
Input : test_list = [“geekforgeekss”, “is”, “bessst”], K = ‘e’
Output : [“geekforgeekss”, “bessst”, “is”]
Explanation : Ordered decreasing order of ‘e’ count.
方法 #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']