python相当于filter()获取两个输出列表(即列表分区) [英] python equivalent of filter() getting two output lists (i.e. partition of a list)

查看:167
本文介绍了python相当于filter()获取两个输出列表(即列表分区)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个列表和一个过滤函数。使用类似于

 >>> filter(lambda x:x> 10,[1,4,12,7,42])
[12,42]

我可以得到符合标准的元素。有没有一个我可以使用的函数会输出两个列表,其中一个元素匹配,其余元素之一?我可以调用 filter()函数两次,但是有点难看:
$ b 编辑:元素的顺序应该是守恒的,我可能有多个相同的元素。

试试这个:

  def分区(pred,iterable):
trues = []
falses = []
对于迭代中的项目:
if pred(item):
trues.append(item)
else:
falses.append(item)
return trues,falses

用法:

 >>> truses,falses = partition(lambda x:x> 10,[1,4,12,7,42])
>>> trues
[12,42]
>>>假设
[1,4,7]

itertools食谱

 来自itertools import filterfalse,tee 

def分区(pred,iterable):
'使用谓词将条目分成虚假条目和真条目'
#分区(is_odd,范围(10)) - > 0 2 4 6 8和1 3 5 7 9
t1,t2 = tee(可迭代)
返回filterfalse(pred,t1),filter(pred,t2)

配方来自Python 3.x文档。在Python 2.x中 filterfalse 被称为 ifilterfalse

Let's say I have a list, and a filtering function. Using something like

>>> filter(lambda x: x > 10, [1,4,12,7,42])
[12, 42]

I can get the elements matching the criterion. Is there a function I could use that would output two lists, one of elements matching, one of the remaining elements? I could call the filter() function twice, but that's kinda ugly :)

Edit: the order of elements should be conserved, and I may have identical elements multiple times.

解决方案

Try this:

def partition(pred, iterable):
    trues = []
    falses = []
    for item in iterable:
        if pred(item):
            trues.append(item)
        else:
            falses.append(item)
    return trues, falses

Usage:

>>> trues, falses = partition(lambda x: x > 10, [1,4,12,7,42])
>>> trues
[12, 42]
>>> falses
[1, 4, 7]

There is also an implementation suggestion in itertools recipes:

from itertools import filterfalse, tee

def partition(pred, iterable):
    'Use a predicate to partition entries into false entries and true entries'
    # partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
    t1, t2 = tee(iterable)
    return filterfalse(pred, t1), filter(pred, t2)

The recipe comes from the Python 3.x documentation. In Python 2.x filterfalse is called ifilterfalse.

这篇关于python相当于filter()获取两个输出列表(即列表分区)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆