2

嗨,我有这段代码,并试图将其重构为声明性的。但是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

那么如何编写这段代码,声明式的方式呢?

4

1 回答 1

2

首先,您可以使用 azip来重写您的循环:

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:])))

但这真的很不合时宜!

于 2020-03-09T09:05:15.540 回答