示例输出:
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
#Output:列表索引超出范围
答案 0 :(得分:1)
您可以使用zip
,
def has22(l):
for i, j in zip(l, l[1:]):
if i == 2 and j == 2:
return True
return False
>>> has22([1, 2, 2])
True
>>> has22([1, 2, 1, 2])
False
>>> has22([2, 1, 2])
False
编辑:@ sabik建议的单行版本
any(i == j == 2 for i, j in zip(l, l[1:]))
答案 1 :(得分:0)
在函数的第一行中,应为:
for x in range(0, len(nums) - 1):
索引超出范围错误的原因是,在上一次迭代中,您的nums[x+1]
超出了数组的范围。
答案 2 :(得分:0)
存在该错误是因为在上一次迭代中,您仍尝试访问x + 1处的项目。随便
for x in range(0, len(nums) - 1):
答案 3 :(得分:0)
使用itertools.groupby
例如:
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