Skip to main content
 首页 » 编程设计

python之检查列表中的项目以查看它们是否彼此相邻

2025年05月04日11lyj

``所以我基本上是想看看 python 列表中的两个项目是否彼此相邻。例如,如果我要查看数字 2 是否在此列表中的某个元素旁边。

example_List = [1,2,2,3,4]

它应该返回 True。到目前为止我有这个

def checkList(List1): 
    for i in range(len(List1 - 1)): 
        if list1[i] == 2 and list1[i+1] == 2: 
            return True 
    return False 

我收到错误,错误:-: 'list' 和 'int' 不支持的操作数类型

谢谢!

请您参考如下方法:

问题出在这部分:

len(List1 - 1) 

你应该把它改成

len(List1) - 1 

您应该对变量 List1 使用相同的大小写。 变化

if list1[i] == 2 and list1[i+1] == 2: 

到:

if List1[i] == 2 and List1[i+1] == 2: