📌  相关文章
📜  Python - 非 K 远距离元素

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

Python - 非 K 远距离元素

给定一个列表,任务是编写一个Python程序来提取所有元素,使得没有元素彼此相距 K 远。

例子:

方法#1:使用循环

在这里,我们迭代所有元素,并使用 in运算符检查每个元素是否有距离它 K 距离的元素,如果找到,则不包含在列表中。

Python3
# Python3 code to demonstrate working of
# Non K distant elements
# Using loop
  
# initializing list
test_list = [8, 10, 16, 20, 3, 1, 7]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 2
  
res = []
for ele in test_list:
  
    # check for K distant
    if ele + K not in test_list and ele - K not in test_list:
        res.append(ele)
  
# printing result
print("The filtered List : " + str(res))


Python3
# Python3 code to demonstrate working of
# Non K distant elements
# Using list comprehension
  
# initializing list
test_list = [8, 10, 16, 20, 3, 1, 7]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 2
  
# using list comprehension to get all elements of non K distance
res = [ele for ele in test_list if ele +
       K not in test_list and ele - K not in test_list]
  
# printing result
print("The filtered List : " + str(res))


输出
The original list is : [8, 10, 16, 20, 3, 1, 7]
The filtered List : [16, 20, 7]

方法#2:使用列表理解

在此,我们使用列表理解使用 1 个 liner 执行过滤和迭代任务。

蟒蛇3

# Python3 code to demonstrate working of
# Non K distant elements
# Using list comprehension
  
# initializing list
test_list = [8, 10, 16, 20, 3, 1, 7]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 2
  
# using list comprehension to get all elements of non K distance
res = [ele for ele in test_list if ele +
       K not in test_list and ele - K not in test_list]
  
# printing result
print("The filtered List : " + str(res))
输出
The original list is : [8, 10, 16, 20, 3, 1, 7]
The filtered List : [16, 20, 7]