Python – 按因子數量對列表進行排序
當需要按因子數量對某列表進行排序時,則可以利用求餘運算子和“len”方法定義使用列表推導計算結果的方法。
示例
以下是對相同內容的說明 −
def factor_count(element): return len([element for index in range(1, element) if element % index == 0]) my_list = [121, 1120, 13540, 221, 1400] print("The list is :") print(my_list) my_list.sort(key=factor_count) print("The result is :") print(my_list)
輸出
The list is : [121, 1120, 13540, 221, 1400] The result is : [121, 221, 13540, 1120, 1400]
說明
定義名為“factor_count”的方法,它將列表的元素作為引數,並返回結果。
在方法的外部定義一個列表,並在控制檯上顯示。
利用“sort”方法對列表進行排序,並將金鑰指定為此前提及的方法。
這是在控制檯上顯示的輸出。
廣告