Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python equivalent of scala partition

Tags:

python

scala

I'm currently porting some Scala code to Python and I am wondering what is the most pythonic way to do something similar to Scala's partition? In particular, in the Scala code I have a situation where I am partitioning a list of items based on whether they return true or false from some filter predicate that I pass in:

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

What is the best way to do something like this in Python?

like image 275
shuttle87 Avatar asked Sep 09 '13 07:09

shuttle87


2 Answers

Scala

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

Python - Using List Comprehension

inGroup = [e for e in items if _filter(e)]
outGroup = [e for e in items if not _filter(e)]
like image 33
Abhijit Avatar answered Sep 28 '22 06:09

Abhijit


Using filter (require two iteration):

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

Simple loop:

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

Example:

>>> items = [1,2,3,4,5]
>>> inGroup, outGroup = partition(items, is_even)
>>> inGroup
[2, 4]
>>> outGroup
[1, 3, 5]
like image 122
falsetru Avatar answered Sep 28 '22 08:09

falsetru