Python - 按最大频率字符对字符串进行排序
给定一个字符串,任务是编写一个Python程序来执行按出现次数最多的字符排序。
Input : test_list = [“geekforgeeks”, “bettered”, “for”, “geeks”]
Output : [‘for’, ‘geeks’, ‘bettered’, ‘geekforgeeks’]
Explanation : 1 < 2 < 3 < 4, is ordering of maximum character occurrence frequency.
Input : test_list = [“geekforgeeks”, “for”, “geeks”]
Output : [‘for’, ‘geeks’, ‘geekforgeeks’]
Explanation : 1 < 2 < 4, is ordering of maximum character occurrence frequency.
方法 #1:使用 sort() + Counter() + max()
在这里,我们使用 sort() 执行就地排序,Counter() 用于计算字符频率,max() 用于获取计算频率的最大值。
Python3
# Python3 code to demonstrate working of
# Sort Strings by maximum frequency character
# Using sort() + Counter() + max()
from collections import Counter
# getting maximum character frequency
def max_freq(arg_str):
res = Counter(arg_str)
return arg_str.count(max(res, key = res.get))
# initializing list
test_list = ["geekforgeeks", "bettered", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# performing sort
test_list.sort(key = max_freq)
# printing result
print("Sorted List : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Sort Strings by maximum frequency character
# Using sorted() + lambda + Counter()
from collections import Counter
# getting maximum character frequency
def max_freq(arg_str):
res = Counter(arg_str)
return arg_str.count(max(arg_str, key = arg_str.get))
# initializing list
test_list = ["geekforgeeks", "bettered", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# performing sort
# lambda function to drive logic
res = sorted(test_list,
key = lambda arg_str : arg_str.count(
max(Counter(arg_str), key = Counter(arg_str).get)))
# printing result
print("Sorted List : " + str(res))
输出:
The original list is : ['geekforgeeks', 'bettered', 'for', 'geeks']
Sorted List : ['for', 'geeks', 'bettered', 'geekforgeeks']
方法 #2:使用 sorted() + lambda + Counter()
在此,我们执行使用 sorted() 和 lambda函数执行排序的任务,以获取单个语句逻辑表达式,避免外部函数调用。
蟒蛇3
# Python3 code to demonstrate working of
# Sort Strings by maximum frequency character
# Using sorted() + lambda + Counter()
from collections import Counter
# getting maximum character frequency
def max_freq(arg_str):
res = Counter(arg_str)
return arg_str.count(max(arg_str, key = arg_str.get))
# initializing list
test_list = ["geekforgeeks", "bettered", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# performing sort
# lambda function to drive logic
res = sorted(test_list,
key = lambda arg_str : arg_str.count(
max(Counter(arg_str), key = Counter(arg_str).get)))
# printing result
print("Sorted List : " + str(res))
输出:
The original list is : ['geekforgeeks', 'bettered', 'for', 'geeks']
Sorted List : ['for', 'geeks', 'bettered', 'geekforgeeks']