📜  用于测试列表中非邻居的Python程序

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

用于测试列表中非邻居的Python程序

给定 teo 元素,编写一个Python程序来检查它们是否作为列表中的邻居出现

例子:

方法#1:使用循环

在这种情况下,我们在迭代列表时检查下一个和前一个元素是否不是 i 或 j。

Python3
# Python3 code to demonstrate working of
# Test for Non-neighbours in List
# Using loop
  
# initializing list
test_list = [3, 7, 2, 1, 4, 5, 7, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing i, j
i, j = 7, 4
  
res = True
for idx in range(1, len(test_list) - 1):
    if test_list[idx] == i:
  
        # check for surrounding element to be j if i
        if test_list[idx - 1] == j or test_list[idx + 1] == j:
            res = False
            break
  
# printing result
print("Are i, j Non-neighbours' : " + str(res))


Python3
# Python3 code to demonstrate working of
# Test for Non-neighbours in List
# Using all()
  
# initializing list
test_list = [3, 7, 2, 1, 4, 5, 7, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing i, j
i, j = 7, 4
  
# checking for preceding and succeeding element 
# not to be j if curr is i
res = all(test_list[idx - 1] != j and test_list[idx + 1] !=
          j for idx in range(1, len(test_list) - 1) if test_list[idx] == i)
  
# printing result
print("Are i, j Non-neighbours' : " + str(res))


输出
The original list is : [3, 7, 2, 1, 4, 5, 7, 9]
Are i, j Non-neighbours' : True

方法 #2:使用all()

这是解决此问题的一种线性方法。在此,我们在 all() 的生成器表达式中使用 all() 执行检查邻居的所有元素的任务。

蟒蛇3

# Python3 code to demonstrate working of
# Test for Non-neighbours in List
# Using all()
  
# initializing list
test_list = [3, 7, 2, 1, 4, 5, 7, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing i, j
i, j = 7, 4
  
# checking for preceding and succeeding element 
# not to be j if curr is i
res = all(test_list[idx - 1] != j and test_list[idx + 1] !=
          j for idx in range(1, len(test_list) - 1) if test_list[idx] == i)
  
# printing result
print("Are i, j Non-neighbours' : " + str(res))
输出
The original list is : [3, 7, 2, 1, 4, 5, 7, 9]
Are i, j Non-neighbours' : True