打印元素的Python程序,这些元素是列表中给定元素的倍数
给定一个列表,这里的任务是编写一个Python程序来提取元素,这些元素是自定义列表中所有元素的倍数。
Input : test_list = [4, 24, 8, 10, 12, 23], div_list = [6, 4]
Output : [24, 12]
Explanation : 24 and 12 divides 6 and 4 both.
Input : test_list = [4, 24, 8, 10, 12, 23], div_list = [6, 4, 7]
Output : []
Explanation : No elements divides 6, 4 and 7.
方法 1:使用列表理解和 all()
在此,我们使用 %运算符和 all() 执行检查所有元素是否为多个元素的任务。列表理解用于遍历所有元素。
Python3
# initializing List
test_list = [4, 24, 8, 10, 12, 23]
# printing original list
print("The original list is : " + str(test_list))
# initializing divisor list
div_list = [6, 4]
# using all() to test for all elements
res = [ele for ele in test_list if all(ele % j == 0 for j in div_list)]
# printing result
print("All elements multiple of divisor list : " + str(res))
Python3
# initializing List
test_list = [4, 24, 8, 10, 12, 23]
# printing original list
print("The original list is : " + str(test_list))
# initializing divisor list
div_list = [6, 4]
# using all() to test for all elements
# using filter() and lambda to perform filtering
res = list(filter(lambda ele: all(ele % j == 0 for j in div_list), test_list))
# printing result
print("All elements multiple of divisor list : " + str(res))
输出:
The original list is : [4, 24, 8, 10, 12, 23]
All elements multiple of divisor list : [24, 12]
方法 2:使用 filter()、lambda 和 all()
在此,我们使用 filter() 和 lambda 执行过滤任务,其余所有操作都按上述方法执行。
蟒蛇3
# initializing List
test_list = [4, 24, 8, 10, 12, 23]
# printing original list
print("The original list is : " + str(test_list))
# initializing divisor list
div_list = [6, 4]
# using all() to test for all elements
# using filter() and lambda to perform filtering
res = list(filter(lambda ele: all(ele % j == 0 for j in div_list), test_list))
# printing result
print("All elements multiple of divisor list : " + str(res))
输出:
The original list is : [4, 24, 8, 10, 12, 23]
All elements multiple of divisor list : [24, 12]