Python - 删除差异大于 K 的元组
给定双元组列表,删除差异大于 K 的对。
Input : test_list = [(4, 8), (1, 7), (9, 12), (3, 12), (2, 10)], K = 6
Output : [(4, 8), (9, 12), (1, 7)]
Explanation : 4 (8 – 4), 3 (12 – 9) and 6 are all not greater than 6, hence retained.
Input : test_list = [(4, 8), (1, 7), (9, 12), (3, 12), (2, 10)], K = 3
Output : [(9, 12)]
Explanation : 3 (12 – 9) is not greater than 3, hence retained.
方法#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))
输出:
The original list is : [(4, 8), (1, 7), (9, 12), (3, 12), (2, 10)]
Tuples List after removal : [(4, 8), (9, 12)]
方法 #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))
输出:
The original list is : [(4, 8), (1, 7), (9, 12), (3, 12), (2, 10)]
Tuples List after removal : [(4, 8), (9, 12)]