繁体   English   中英

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

但这真的是非Pythonic!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM