相当于scala分区的python

相当于scala分区的python,python,scala,Python,Scala,我目前正在将一些Scala代码移植到Python中,我想知道什么是做类似于Scala的分区?特别是,在Scala代码中,我遇到了一种情况,即根据我传入的某个过滤器谓词返回的是true还是false对项目列表进行分区: val (inGroup,outGroup) = items.partition(filter) 在Python中执行类似操作的最佳方法是什么?Scala val (inGroup,outGroup) = items.partition(filter) Python-使用列表理

我目前正在将一些Scala代码移植到Python中,我想知道什么是做类似于Scala的
分区
?特别是,在Scala代码中,我遇到了一种情况,即根据我传入的某个过滤器谓词返回的是true还是false对项目列表进行分区:

val (inGroup,outGroup) = items.partition(filter)
在Python中执行类似操作的最佳方法是什么?

Scala

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(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]
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导入ifilterfalse、ifilter、islice、tee、count
def分区(pred,iterable):
'''
>>>is_偶数=lambda i:i%2==0
>>>偶数,无偶数=分区(是偶数,xrange(11))
>>>列表(偶数)
[0, 2, 4, 6, 8, 10]
>>>列表(无偶数)
[1, 3, 5, 7, 9]
#惰性评估
>>>infi_列表=计数(0)
>>>ingroup,outgroup=分区(是偶数,infi\u列表)
>>>列表(islice(内部组,5))
[0, 2, 4, 6, 8]
>>>列表(islice(外部组,5))
[1, 3, 5, 7, 9]
'''
t1,t2=三通(可调)
返回ifilter(pred,t1),ifilterfalse(pred,t2)

此版本是惰性的,不会对同一元素应用两次谓词:

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)
例如:

>>> items = [1,2,3,4,5]
>>> inGroup, outGroup = partition(items, is_even)
>>> inGroup
[2, 4]
>>> outGroup
[1, 3, 5]
even = lambda x: x % 2 == 0

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

尝试
打印(列表(zip(o,e))
。它应该打印
[(1,2)、(1,2)、(1,2)、(1,2)、(1,2)]
,但它打印
[(1,2)、(1,2)]
。要解决这个问题,请将第一个
while
循环放入第二个
while
循环。filterfalse在哪里?澄清一些让我困惑的问题:在“简单循环”代码中,你的意思是写
if is_偶数(n):
还是
if filter_(n):
@shuttle87,我的意思是写
if filter_(n)
。我修正了,可能是重复的