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

Python declarative loop refactor (need access multiple elements)

您好,我有这段代码,正在尝试将其重构为声明式的。但是 AFAIK,所有像 map() reduce() filter() 这样的声明性方法都会遍历容器的每个元素,像这样

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

那么这段代码怎么写,声明式的?

首先,您可以使用 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:])))

但这真的 unpythonic!