Python声明性循环重构(需要访问多个元素)

2024-04-29 04:47:51 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我有这段代码,并试图将其重构为声明性的。但是,像map(){}{}这样的所有声明性方法都将在容器的每个元素中循环,不是像这样的少数方法

def arrayCheck(nums):

    # Note: iterate with length-2, so can use i+1 and i+2 in the loop
    for i in range(len(nums)-2):
        # Check in sets of 3 if we have 1,2,3 in a row
        if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
            return True
    return False

那么,如何以声明的方式编写此代码呢


Tags: and方法代码in声明元素mapreturn
1条回答
网友
1楼 · 发布于 2024-04-29 04:47:51

首先,可以使用zip重写循环:

def array_check(nums):
    for a, b, c in zip(nums, nums[1:], nums[2:]):
        if a == 1 and b == 2 and c == 3:
            return True
    return False

然后,使用元组比较:

def array_check(nums):
    for a, b, c in zip(nums, nums[1:], nums[2:]):
        if (a, b, c) == (1, 2, 3):
            return True
    return False

然后是any内置的:

def array_check(nums):
    return any((a, b, c) == (1, 2, 3) for a, b, c in zip(nums, nums[1:], nums[2:]))

测试:

>>> array_check([1,3,4,1,2,3,5])
True
>>> array_check([1,3,4,1,3,5])
False

注:有关更快的版本,请参阅下面的@juanpa.arrivillaga注释


如果您想模仿功能性风格:

import operator, functools

def array_check(nums):
    return any(map(functools.partial(operator.eq, (1,2,3)), zip(nums, nums[1:], nums[2:])))

但那真的是不和谐的

相关问题 更多 >