根據唯一字元數對字串列表排序的 Python 程式
當需要根據唯一字元數對字串列表排序時,定義了一個使用'set'運算子,'list'方法和'len'方法的方法。
示例
以下是對它的演示 −
def my_sort_func(my_elem): return len(list(set(my_elem))) my_list = ['python', "Will", "Hi", "how", 'fun', 'learn', 'code'] print("The list is : ") print(my_list) my_list.sort(key = my_sort_func) print("The result is :") print(my_list)
輸出
The list is : ['python', 'Will', 'Hi', 'how', 'fun', 'learn', 'code'] The result is : ['Hi', 'Will', 'how', 'fun', 'code', 'learn', 'python']
說明
定義了一個名為'my_sort_func'的方法,它將一個字串作為引數。
它首先使用“set'從列表中提取唯一元素,並將其轉換為一個集合,然後提取列表的長度。
在此方法之外,定義了一個字串列表並在控制檯上顯示。
透過將鍵指定為先前定義的方法來對列表進行排序。
結果顯示在控制檯上。
廣告