📜  Python - 删除差异大于 K 的元组

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

Python - 删除差异大于 K 的元组

给定双元组列表,删除差异大于 K 的对。

方法#1:使用列表理解

在这种情况下,我们通过使用abs()测试绝对差异来执行过滤,如果发现小于 K,则保留它,因此删除大于 K 的差异元组。

Python3
# Python3 code to demonstrate working of
# Remove Tuples with difference greater than K
# Using list comprehension
  
# initializing list
test_list = [(4, 8), (1, 7), (9, 12), (3, 12), (2, 10)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 5
  
# filtering using list comprehension, checking for smaller than K diff.
res = [sub for sub in test_list if abs(sub[0] - sub[1]) <= K]
  
# printing result
print("Tuples List after removal : " + str(res))


Python3
# Python3 code to demonstrate working of
# Remove Tuples with difference greater than K
# Using filter() + lambda + abs()
  
# initializing list
test_list = [(4, 8), (1, 7), (9, 12), (3, 12), (2, 10)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 5
  
# Using filter() and lambda function for filtering
res = list(filter(lambda sub: abs(sub[0] - sub[1]) <= K, test_list))
  
# printing result
print("Tuples List after removal : " + str(res))


输出:

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

在这里,过滤任务是使用filter()lambda函数执行的, abs()用于获取绝对差异。

蟒蛇3

# Python3 code to demonstrate working of
# Remove Tuples with difference greater than K
# Using filter() + lambda + abs()
  
# initializing list
test_list = [(4, 8), (1, 7), (9, 12), (3, 12), (2, 10)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 5
  
# Using filter() and lambda function for filtering
res = list(filter(lambda sub: abs(sub[0] - sub[1]) <= K, test_list))
  
# printing result
print("Tuples List after removal : " + str(res))

输出: