Python - 过滤元组乘积大于 K
给定一个元组列表,提取所有乘积大于 K 的内容。
Input : test_list = [(4, 5, 7), (1, 2, 3), (8, 4, 2), (2, 3, 4)], K = 50
Output : [(4, 5, 7), (8, 4, 2)]
Explanation : 140 and 64 are greater than 50, hence tuples extracted.
Input : test_list = [(4, 5, 7), (1, 2, 3), (8, 4, 2), (2, 3, 4)], K = 100
Output : [(4, 5, 7)]
Explanation : 140 is greater than 100, hence tuple extracted.
方法#1:使用列表理解
在这里,我们使用外部函数提取所有大于 K 乘积的元组。
Python3
# Python3 code to demonstrate working of
# Filter Tuples Product greater than K
# Using list comprehension
# getting product
def prod(box):
res = 1
for ele in box:
res *= ele
return res
# initializing list
test_list = [(4, 5, 7), (1, 2, 3), (8, 4, 2), (2, 3, 4)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 50
res = [sub for sub in test_list if prod(sub) > K]
# printing result
print("Tuples with product greater than K : " + str(res))
Python3
# Python3 code to demonstrate working of
# Filter Tuples Product greater than K
# Using filter() + lambda
# getting product
def prod(box):
res = 1
for ele in box:
res *= ele
return res
# initializing list
test_list = [(4, 5, 7), (1, 2, 3), (8, 4, 2), (2, 3, 4)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 50
# using filter() to get products greater than K
res = list(filter(lambda sub : prod(sub) > K, test_list))
# printing result
print("Tuples with product greater than K : " + str(res))
输出:
The original list is : [(4, 5, 7), (1, 2, 3), (8, 4, 2), (2, 3, 4)]
Tuples with product greater than K : [(4, 5, 7), (8, 4, 2)]
方法 #2:使用 filter() + lambda
在这种情况下,过滤元组的任务是使用filter()和lambda完成的,乘积以类似的方式计算。
蟒蛇3
# Python3 code to demonstrate working of
# Filter Tuples Product greater than K
# Using filter() + lambda
# getting product
def prod(box):
res = 1
for ele in box:
res *= ele
return res
# initializing list
test_list = [(4, 5, 7), (1, 2, 3), (8, 4, 2), (2, 3, 4)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 50
# using filter() to get products greater than K
res = list(filter(lambda sub : prod(sub) > K, test_list))
# printing result
print("Tuples with product greater than K : " + str(res))
输出:
The original list is : [(4, 5, 7), (1, 2, 3), (8, 4, 2), (2, 3, 4)]
Tuples with product greater than K : [(4, 5, 7), (8, 4, 2)]