📌  相关文章
📜  Python - 按大小写差异对字符串进行排序

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

Python - 按大小写差异对字符串进行排序

给定字符串列表,任务是编写一个Python程序来执行基于大小写差异的排序,即小写和大写的计数。

例子:

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

在这种就地排序中,使用 sort() 执行,而 islower() 和 isupper() 用于检查案例和计数。然后 abs() 用于获取提供参数以执行排序的绝对差异。

Python3
# Python3 code to demonstrate working of
# Sort Strings by Case difference
# Using sort() + islower() + isupper() + abs()
  
  
def get_case_diff(string):
  
    # getting case count and difference
    lower_cnt = len([ele for ele in string if ele.islower()])
    upper_cnt = len([ele for ele in string if ele.isupper()])
    return abs(lower_cnt - upper_cnt)
  
  
# initializing Matrix
test_list = ["GFG", "GeeKs", "best", "FOr", "alL", "GEEKS"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# inplace sort using sort()
test_list.sort(key=get_case_diff)
  
# printing result
print("Sorted Strings by case difference : " + str(test_list))


Python3
# Python3 code to demonstrate working of
# Python3 code to demonstrate working of
# Sort Strings by Case difference
# Using sorted() + lambda + islower() + len() + isupper() + abs()
  
# initializing Matrix
test_list = ["GFG", "GeeKs", "best", "FOr", "alL", "GEEKS"]
              
# printing original list
print("The original list is : " + str(test_list))
  
# sorting using sorted()
# lambda function to inject functionality
res = sorted(test_list, key = lambda string : \
        abs(len([ele for ele in string if ele.islower()]) - \
        len([ele for ele in string if ele.isupper()])))
  
# printing result
print("Sorted Strings by case difference : " + str(res))


输出:

方法#2:使用 sorted() + lambda + islower() + len() + isupper() + abs()

与上述方法类似,不同之处在于使用的排序方式、sorted() 和 lambda 用作注入功能的方式。

蟒蛇3

# Python3 code to demonstrate working of
# Python3 code to demonstrate working of
# Sort Strings by Case difference
# Using sorted() + lambda + islower() + len() + isupper() + abs()
  
# initializing Matrix
test_list = ["GFG", "GeeKs", "best", "FOr", "alL", "GEEKS"]
              
# printing original list
print("The original list is : " + str(test_list))
  
# sorting using sorted()
# lambda function to inject functionality
res = sorted(test_list, key = lambda string : \
        abs(len([ele for ele in string if ele.islower()]) - \
        len([ele for ele in string if ele.isupper()])))
  
# printing result
print("Sorted Strings by case difference : " + str(res))

输出: