python 相当于 filter() 获取两个输出列表(即列表的分区) [英] python equivalent of filter() getting two output lists (i.e. partition of a list)
问题描述
假设我有一个列表和一个过滤功能.使用类似
<预><代码>>>>过滤器(λ x:x > 10,[1,4,12,7,42])[12, 42]我可以获得符合条件的元素.有没有我可以使用的函数来输出两个列表,一个匹配的元素,一个剩余的元素?我可以调用 filter()
函数两次,但这有点难看 :)
元素的顺序应该是守恒的,我可能有多次相同的元素.
试试这个:
def partition(pred, iterable):真= []假= []对于可迭代项目:如果预测(项目):trues.append(item)别的:falses.append(item)返回真,假
用法:
<预><代码>>>>trues, falses = partition(lambda x: x > 10, [1,4,12,7,42])>>>真的[12, 42]>>>假的[1, 4, 7]itertools recipes 中还有一个实现建议:
from itertools import filterfalse, tee定义分区(pred,可迭代):'使用谓词将条目划分为虚假条目和真实条目'# partition(is_odd, range(10)) -->0 2 4 6 8 和 1 3 5 7 9t1, 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屋!