📜  Python - 提取极值差异大于 K 的列表

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

Python - 提取极值差异大于 K 的列表

给定一个列表列表。任务是过滤所有最小值和最大值之差大于 K 的行。

例子:

方法 #1:使用列表理解+ min() + max()

在这里,我们使用列表理解执行迭代任务,并使用运算符完成检查任务。使用 max() 和 min() 计算值。

Python3
# Python3 code to demonstrate working of 
# Filter rows with Extreme values greater than K
# Using min() + max() + list comprehension
  
# initializing list
test_list = [[3, 5, 1], [9, 1, 2], [3, 4, 2], [1, 10, 2]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 5
  
# max() and min() getting extreme difference
res = [sub for sub in test_list if max(sub) - min(sub) > K]
  
# printing result 
print("Filtered rows : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Filter rows with Extreme values greater than K
# Using filter() + lambda + min() + max()
  
# initializing list
test_list = [[3, 5, 1], [9, 1, 2], [3, 4, 2], [1, 10, 2]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 5
  
# max() and min() getting extreme difference
res = list(filter(lambda sub : max(sub) - min(sub) > K, test_list))
  
# printing result 
print("Filtered rows : " + str(res))


输出:

方法#2:使用 filter() + lambda + min() + max()

在此,我们使用 filter() 和 lambda 执行过滤任务,rest min() 和 max() 用于获得极值差异。

蟒蛇3

# Python3 code to demonstrate working of 
# Filter rows with Extreme values greater than K
# Using filter() + lambda + min() + max()
  
# initializing list
test_list = [[3, 5, 1], [9, 1, 2], [3, 4, 2], [1, 10, 2]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 5
  
# max() and min() getting extreme difference
res = list(filter(lambda sub : max(sub) - min(sub) > K, test_list))
  
# printing result 
print("Filtered rows : " + str(res))

输出: