Python - 提取相对差异大于 K 的元素
给定一个数字列表,任务是编写一个Python程序来提取所有具有当前大于 K 的下一个和上一个元素的差异的数字。
Input : test_list = [2, 7, 4, 1, 9, 2, 3, 10, 1, 5], K = 4
Output : [9, 10]
Explanation : 9 has 1 as preceding element and 2 as succeeding. 8 and 7 are its difference respectively which are greater than 4.
Input : test_list = [2, 7, 4, 1, 9, 2], K = 4
Output : [9]
Explanation : 9 has 1 as preceding element and 2 as succeeding. 8 and 7 are its difference respectively which are greater than 4.
方法#1:使用循环
在此,我们使用蛮力检查下一个或前一个元素是否具有小于 K 差的元素并忽略它们。循环用于所有元素的迭代。
Python3
# Python3 code to demonstrate working of
# Extract element with relative difference
# greater than K Using loop
# initializing list
test_list = [2, 7, 4, 1, 9, 2, 3, 10, 1, 5]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
res = []
for idx in range(1, len(test_list)):
# using abs to get absolute difference
if abs(test_list[idx - 1] - test_list[idx]) > K\
and abs(test_list[idx + 1] - test_list[idx]) > K:
res.append(test_list[idx])
# printing result
print("The extracted difference elements : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract element with relative difference
# greater than K Using list comprehension
# initializing list
test_list = [2, 7, 4, 1, 9, 2, 3, 10, 1, 5]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# using abs to get absolute difference
# list comprehension provides shorthand
res = [test_list[idx] for idx in range(
1, len(test_list)) if abs(test_list[idx - 1] - test_list[idx]) > K
and abs(test_list[idx + 1] - test_list[idx]) > K]
# printing result
print("The extracted difference elements : " + str(res))
输出:
The original list is : [2, 7, 4, 1, 9, 2, 3, 10, 1, 5]
The extracted difference elements : [9, 10]
方法#2:使用列表理解
这与上述方法类似,区别仅在于使用列表理解来解决问题的速记。
蟒蛇3
# Python3 code to demonstrate working of
# Extract element with relative difference
# greater than K Using list comprehension
# initializing list
test_list = [2, 7, 4, 1, 9, 2, 3, 10, 1, 5]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# using abs to get absolute difference
# list comprehension provides shorthand
res = [test_list[idx] for idx in range(
1, len(test_list)) if abs(test_list[idx - 1] - test_list[idx]) > K
and abs(test_list[idx + 1] - test_list[idx]) > K]
# printing result
print("The extracted difference elements : " + str(res))
输出:
The original list is : [2, 7, 4, 1, 9, 2, 3, 10, 1, 5]
The extracted difference elements : [9, 10]