Python – 區分大小寫對字串進行排序
在需要根據大小寫差異對字串進行排序時,可以定義一種將字串作為引數的方法。此方法使用列表解析和 isupper 和 islower 方法以及列表解析來獲取大小寫差異。它們的差異會產生排序值。
示例
以下是同一部署的演示
def get_diff(my_string): lower_count = len([ele for ele in my_string if ele.islower()]) upper_count = len([ele for ele in my_string if ele.isupper()]) return abs(lower_count - upper_count) my_list = ["Abc", "Python", "best", "hello", "coders"] print("The list is :") print(my_list) my_list.sort(key=get_diff) print("Sorted Strings by case difference :") print(my_list)
輸出
The list is : ['Abc', 'Python', 'best', ‘hello’, 'coders'] Sorted Strings by case difference : ['Abc', 'Python', 'best', 'coders', ‘hello’]
說明
定義了一種名為 get_diff 的方法,它將字串列表作為引數。
列表解析和 islower 和 isupper 方法用於檢查字串是是大寫還是小寫。
將這些值儲存在兩個不同的變數中。
這兩個變數之間的絕對差異作為輸出返回。
在此方法之外,定義一個列表並將其顯示在控制檯上。
列表是根據先前定義的方法排序的。
這是顯示在控制檯上的輸出。
廣告