📜  Python - 用 N 删除 K 距离内的元素

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

Python - 用 N 删除 K 距离内的元素

给定一个列表,用 N 删除 K 距离内的所有元素。

方法#1:使用列表理解

在这种情况下,我们使用列表理解进行比较,仅提取那些处于安全距离 K 到 N 的元素。

Python3
# Python3 code to demonstrate working of 
# Remove Elements in K distance with N
# Using list comprehension
  
# initializing list
test_list = [4, 5, 9, 1, 10, 6, 13 ]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 3
  
# initializing N 
N = 5
  
# checking for elements in safe zone with respect to N
res = [ele for ele in test_list if ele < N - K or ele > N + K]
  
# printing result 
print("Filtered elements : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Remove Elements in K distance with N
# Using filter() + lambda
  
# initializing list
test_list = [4, 5, 9, 1, 10, 6, 13 ]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 3
  
# initializing N 
N = 5
  
# checking for elements in safe zone with respect to N
res = list(filter(lambda ele : ele < N - K or ele > N + K, test_list))
  
# printing result 
print("Filtered elements : " + str(res))


输出
The original list is : [4, 5, 9, 1, 10, 6, 13]
Filtered elements : [9, 1, 10, 13]

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

在这里,过滤任务是使用 filter() 和 lambda函数完成的。

蟒蛇3

# Python3 code to demonstrate working of 
# Remove Elements in K distance with N
# Using filter() + lambda
  
# initializing list
test_list = [4, 5, 9, 1, 10, 6, 13 ]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 3
  
# initializing N 
N = 5
  
# checking for elements in safe zone with respect to N
res = list(filter(lambda ele : ele < N - K or ele > N + K, test_list))
  
# printing result 
print("Filtered elements : " + str(res))
输出
The original list is : [4, 5, 9, 1, 10, 6, 13]
Filtered elements : [9, 1, 10, 13]