gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:55:04 25 4
gpt4 key购买 nike

``所以我基本上是想看看 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:

关于python - 检查列表中的项目以查看它们是否彼此相邻,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32533820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com