📜  Python - 过滤元组乘积大于 K

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

Python - 过滤元组乘积大于 K

给定一个元组列表,提取所有乘积大于 K 的内容。

方法#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))


输出:

方法 #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))

输出: