简体   繁体   English

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

[英]Python declarative loop refactor (need access multiple elements)

Hi I have this piece of code and trying to refactor it to be declarative.嗨,我有这段代码并试图将其重构为声明性的。 But AFAIK, all declarative methods like map() reduce() filter() will loop through each element of the container, not a few like this但是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

So how to write this code, declarative way?那么如何编写这段代码,声明式的方式呢?

First, you can use a zip to rewrite your loop:首先,您可以使用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

Then, use the tuple comparison:然后,使用元组比较:

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

And then the any builtin:然后是any内置:

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

Test:测试:

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

Note: for a faster version, see @juanpa.arrivillaga comment below.注意:对于更快的版本,请参阅下面的@juanpa.arrivillaga 评论。


If you want to mimic functional style:如果你想模仿功能风格:

import operator, functools

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

But that's really unpythonic!但这真的是非Pythonic!

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

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