用于从元组列表中查找所有元素都可被 K 整除的元组的Python程序
给定一个元组列表。任务是提取所有元素可被 K 整除的所有元组。
Input : test_list = [(6, 24, 12), (60, 12, 6), (12, 18, 21)], K = 6
Output : [(6, 24, 12), (60, 12, 6)]
Explanation : Both tuples have all elements multiple of 6.
Input : test_list = [(6, 24, 12), (60, 10, 5), (12, 18, 21)], K = 5
Output : [(60, 10, 5)]
Explanation : Multiple of 5 tuples extracted.
方法 #1:使用列表理解 + all()
在此,我们使用 all() 测试所有元素是否为 K 倍数以用于过滤目的,列表推导用于所有元组的迭代。
Python3
# Python3 code to demonstrate working of
# K Multiple Elements Tuples
# Using list comprehension + all()
# initializing list
test_list = [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 6
# all() used to filter elements
res = [sub for sub in test_list if all(ele % K == 0 for ele in sub)]
# printing result
print("K Multiple elements tuples : " + str(res))
Python3
# Python3 code to demonstrate working of
# K Multiple Elements Tuples
# Using filter() + lambda + all()
# initializing list
test_list = [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 6
# filter() + lambda for filter operation
res = list(filter(lambda sub: all(ele % K == 0 for ele in sub), test_list))
# printing result
print("K Multiple elements tuples : " + str(res))
输出
The original list is : [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
K Multiple elements tuples : [(6, 24, 12)]
方法 #2:使用 filter() + lambda + all()
在此,我们使用 filter() + lambda 和 all() 提供的逻辑执行过滤任务,如上述方法。
Python3
# Python3 code to demonstrate working of
# K Multiple Elements Tuples
# Using filter() + lambda + all()
# initializing list
test_list = [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 6
# filter() + lambda for filter operation
res = list(filter(lambda sub: all(ele % K == 0 for ele in sub), test_list))
# printing result
print("K Multiple elements tuples : " + str(res))
输出
The original list is : [(6, 24, 12), (7, 9, 6), (12, 18, 21)]
K Multiple elements tuples : [(6, 24, 12)]