📜  Python - 按大写频率排序

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

Python - 按大写频率排序

给定一个字符串列表,按大写字符的频率执行排序。

方法 #1:使用 sort() + isupper()

在此,我们使用isupper()执行检查大写的任务,并使用sort()执行排序任务。

Python3
# Python3 code to demonstrate working of
# Sort by Uppercase Frequency
# Using isupper() + sort()
  
  
# helper function
def upper_sort(sub):
  
    # len() to get total uppercase characters
    return len([ele for ele in sub if ele.isupper()])
  
  
# initializing list
test_list = ["Gfg", "is", "BEST", "FoR", "GEEKS"]
  
# printing original list
print("The original list is: " + str(test_list))
  
# using external function to perform sorting
test_list.sort(key=upper_sort)
  
# printing result
print("Elements after uppercase sorting: " + str(test_list))


Python3
# Python3 code to demonstrate working of
# Sort by Uppercase Frequency
# Using sorted() + lambda function
  
  
# initializing list
test_list = ["Gfg", "is", "BEST", "FoR", "GEEKS"]
  
# printing original list
print("The original list is: " + str(test_list))
  
# sorted() + lambda function used to solve problem
res = sorted(test_list, key=lambda sub: len(
    [ele for ele in sub if ele.isupper()]))
  
# printing result
print("Elements after uppercase sorting: " + str(res))


输出:

The original list is: ['Gfg', 'is', 'BEST', 'FoR', 'GEEKS']
Elements after uppercase sorting: ['is', 'Gfg', 'FoR', 'BEST', 'GEEKS']

方法#2:使用 sorted() + lambda函数

在这里,我们使用sorted()执行排序任务,并且使用lambda函数而不是外部sort()函数来执行排序任务。

蟒蛇3

# Python3 code to demonstrate working of
# Sort by Uppercase Frequency
# Using sorted() + lambda function
  
  
# initializing list
test_list = ["Gfg", "is", "BEST", "FoR", "GEEKS"]
  
# printing original list
print("The original list is: " + str(test_list))
  
# sorted() + lambda function used to solve problem
res = sorted(test_list, key=lambda sub: len(
    [ele for ele in sub if ele.isupper()]))
  
# printing result
print("Elements after uppercase sorting: " + str(res))

输出:

The original list is: ['Gfg', 'is', 'BEST', 'FoR', 'GEEKS']
Elements after uppercase sorting: ['is', 'Gfg', 'FoR', 'BEST', 'GEEKS']