我目前正在将一些
Scala代码移植到
Python中,我想知道什么是最类似于Scala分区的pythonic方法?特别是,在Scala代码中我有一种情况,我根据是否从我传入的某个过滤谓词返回true或false来分区项目列表:
val (inGroup,outGroup) = items.partition(filter)
在Python中做这样的事情的最佳方法是什么?
解决方法@H_502_8@
使用过滤器(需要两次迭代):
>>> 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,5]
>>> inGroup,outGroup = partition(items,is_even)
>>> inGroup
[2,4]
>>> outGroup
[1,5]
>>> 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,5] >>> inGroup,outGroup = partition(items,is_even) >>> inGroup [2,4] >>> outGroup [1,5]