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?
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)]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With