📌  相关文章
📜  Python - 因子数小于 K 的元素

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

Python - 因子数小于 K 的元素

给定一个元素列表,获取所有因子小于 K 的元素。

例子:

方法#1:使用列表理解

在这里,我们使用列表理解来获取因子计数,并使用其他列表理解来迭代列表中的所有元素。

Python3
# Python3 code to demonstrate working of
# Elements with factors less than K
# Using list comprehension
  
  
def factors_less_k(ele, K):
  
    # comparing for factors
    return len([idx for idx in range(1, ele + 1) if ele % idx == 0]) <= K
  
  
# initializing list
test_list = [60, 12, 100, 17, 18]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 4
  
# checking for each element
res = [ele for ele in test_list if factors_less_k(ele, K)]
  
# printing result
print("Filtered elements : " + str(res))


Python3
# Python3 code to demonstrate working of
# Elements with factors less than K
# Using filter() + lambda + len() + list comprehension
  
  
def factors_less_k(ele, K):
  
    # comparing for factors
    return len([idx for idx in range(1, ele + 1) if ele % idx == 0]) <= K
  
  
# initializing list
test_list = [60, 12, 100, 17, 18]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 4
  
# filtering using filter() + lambda
res = list(filter(lambda ele: factors_less_k(ele, K), test_list))
  
# printing result
print("Filtered elements : " + str(res))


输出
The original list is : [60, 12, 100, 17, 18]
Filtered elements : [17]

方法 #2:使用filter() + lambda + len() + 列表理解

其中,过滤任务是使用 filter() 和 lambda、len() 完成的,并且使用列表理解来执行获取因子的任务。

蟒蛇3

# Python3 code to demonstrate working of
# Elements with factors less than K
# Using filter() + lambda + len() + list comprehension
  
  
def factors_less_k(ele, K):
  
    # comparing for factors
    return len([idx for idx in range(1, ele + 1) if ele % idx == 0]) <= K
  
  
# initializing list
test_list = [60, 12, 100, 17, 18]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 4
  
# filtering using filter() + lambda
res = list(filter(lambda ele: factors_less_k(ele, K), test_list))
  
# printing result
print("Filtered elements : " + str(res))
输出
The original list is : [60, 12, 100, 17, 18]
Filtered elements : [17]