簡體   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