簡體   English   中英

python相當於scala分區

[英]python equivalent of scala partition

我目前正在將一些Scala代碼移植到Python中,我想知道什么是最類似於Scala partition pythonic方法? 特別是,在Scala代碼中我有一種情況,我根據是否從我傳入的某個過濾謂詞返回true或false來分區項目列表:

val (inGroup,outGroup) = items.partition(filter)

在Python中做這樣的事情的最佳方法是什么?

使用過濾器(需要兩次迭代):

>>> items = [1,2,3,4,5]
>>> inGroup = filter(is_even, items) # list(filter(is_even, items)) in Python 3.x
>>> outGroup = filter(lambda n: not is_even(n), items)
>>> inGroup
[2, 4]
>>> outGroup

簡單循環:

def partition(item, filter_):
    inGroup, outGroup = [], []
    for n in items:
        if filter_(n):
            inGroup.append(n)
        else:
            outGroup.append(n)
    return inGroup, outGroup

例:

>>> items = [1,2,3,4,5]
>>> inGroup, outGroup = partition(items, is_even)
>>> inGroup
[2, 4]
>>> outGroup
[1, 3, 5]

斯卡拉

val (inGroup,outGroup) = items.partition(filter)

Python - 使用列表理解

inGroup = [e for e in items if _filter(e)]
outGroup = [e for e in items if not _filter(e)]

此版本是惰性的,不會將謂詞兩次應用於同一元素:

def partition(it, pred):
    buf = [[], []]
    it = iter(it)

    def get(t):
        while True:
            while buf[t]:
                yield buf[t].pop(0)
            x = next(it)
            if t == bool(pred(x)):
                yield x
            else:
                buf[not t].append(x)

    return get(True), get(False)

例:

even = lambda x: x % 2 == 0

e, o = partition([1,1,1,2,2,2,1,2], even)
print list(e)
print list(o)

Scala有豐富的列表處理API,而Python也是如此。

你應該閱讀文檔itertools 你可能會發現一個分區。

from itertools import ifilterfalse, ifilter, islice, tee, count

def partition(pred, iterable):
    '''
    >>> is_even = lambda i: i % 2 == 0
    >>> even, no_even = partition(is_even, xrange(11))
    >>> list(even)
    [0, 2, 4, 6, 8, 10]
    >>> list(no_even)
    [1, 3, 5, 7, 9]

    # Lazy evaluation
    >>> infi_list = count(0)
    >>> ingroup, outgroup = partition(is_even, infi_list)
    >>> list(islice(ingroup, 5))
    [0, 2, 4, 6, 8]
    >>> list(islice(outgroup, 5))
    [1, 3, 5, 7, 9]
    '''
    t1, t2 = tee(iterable)
    return ifilter(pred, t1), ifilterfalse(pred, t2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM