📜  Python - 按因子计数排序

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

Python - 按因子计数排序

给定元素列表,按每个元素的因子计数排序。

方法 #1:使用 sort() + len() + 列表理解

在这里,我们使用sort()执行排序任务, len()和列表推导用于获取因子计数的任务。

Python3
# Python3 code to demonstrate working of
# Sort by Factor count
# Using sort() + len() + list comprehension
  
  
def factor_count(ele):
  
    # getting factors count
    return len([ele for idx in range(1, ele) if ele % idx == 0])
  
  
# initializing list
test_list = [12, 100, 360, 22, 200]
  
# printing original list
print("The original list is : " + str(test_list))
  
# performing sort
test_list.sort(key=factor_count)
  
# printing result
print("Sorted List : " + str(test_list))


Python3
# Python3 code to demonstrate working of
# Sort by Factor count
# Using lambda + sorted() + len()
  
# initializing list
test_list = [12, 100, 360, 22, 200]
  
# printing original list
print("The original list is : " + str(test_list))
  
# performing sort using sorted(), lambda getting factors
res = sorted(test_list, key=lambda ele: len(
    [ele for idx in range(1, ele) if ele % idx == 0]))
  
# printing result
print("Sorted List : " + str(res))


输出:

The original list is : [12, 100, 360, 22, 200]
Sorted List : [22, 12, 100, 200, 360]

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

在这种情况下,排序任务是使用sorted()完成的,并且使用 lambda函数馈送到 sorted 以获取因子。

蟒蛇3

# Python3 code to demonstrate working of
# Sort by Factor count
# Using lambda + sorted() + len()
  
# initializing list
test_list = [12, 100, 360, 22, 200]
  
# printing original list
print("The original list is : " + str(test_list))
  
# performing sort using sorted(), lambda getting factors
res = sorted(test_list, key=lambda ele: len(
    [ele for idx in range(1, ele) if ele % idx == 0]))
  
# printing result
print("Sorted List : " + str(res))

输出:

The original list is : [12, 100, 360, 22, 200]
Sorted List : [22, 12, 100, 200, 360]