Python 确定是否有两个2';在一个数组中,它彼此相邻

Python 确定是否有两个2';在一个数组中,它彼此相邻,python,arrays,list,Python,Arrays,List,示例输出: has22([1, 2, 2]) → True has22([1, 2, 1, 2]) → False has22([2, 1, 2]) → False 我的代码: def has22(nums): for x in range(0, len(nums)): if nums[x] == 2 and (nums[x+1] == 2): return True return False #输出:列出超出范围的索引您可以使

示例输出:

has22([1, 2, 2]) → True

has22([1, 2, 1, 2]) → False

has22([2, 1, 2]) → False
我的代码:

def has22(nums):

    for x in range(0, len(nums)):
        if nums[x] == 2 and (nums[x+1] == 2):
            return True
    return False 
#输出:列出超出范围的索引

您可以使用



编辑:由@sabik建议的一个线性版本

any(i == j == 2 for i, j in zip(l, l[1:]))

函数的第一行应该是:
范围(0,len(nums)-1)内的x的


索引超出范围错误的原因是,在上一次迭代中,您的
nums[x+1]
超出了数组的范围。

存在此错误,因为在上一次迭代中,您仍在尝试访问x+1处的项。照办

for x in range(0, len(nums) - 1):

使用
itertools.groupby

Ex:

from itertools import groupby

def has22(lst):
    return any(k==2 and len(list(v)) ==2 for k,v in groupby(lst))
        
print(has22([1, 2, 2]))
print(has22([1, 2, 1, 2]))
print(has22([2, 1, 2]))
True
False
False
输出:

from itertools import groupby

def has22(lst):
    return any(k==2 and len(list(v)) ==2 for k,v in groupby(lst))
        
print(has22([1, 2, 2]))
print(has22([1, 2, 1, 2]))
print(has22([2, 1, 2]))
True
False
False

对于范围(0,len(nums)-1)内的x
这也可以转换为一行:
any(i==j==2,对于zip中的i,j(l,l[1:])
作为旁注,最好避免使用变量名
l
,因为它在某些字体中可能类似于数字
1