分裂过滤器功能?

发布于 2025-02-08 18:39:37 字数 136 浏览 0 评论 0原文

是否有一些功能充当过滤器,但也返回被拒绝的值列表?例如,我可能想执行大于5分的列表之类的事情。如下所示:

seliver = splitFilter(lambda x:x< 5,a)

Is there some function that acts as filter but also returns the list of rejected values? For example, I might want to do something like split a list into values greater and lower than 5. So if I have an array a I might say apply this hypothetical function splitfilter as follows:

lower, higher = splitfilter(lambda x: x<5, a)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无人问我粥可暖 2025-02-15 18:39:37

据我所知,此功能不是内置的。如果我们要热切地消耗输入峰值并以输出形式产生列表,那么写这是相当简单的。

def splitfilter(p, xs):
  t, f = [], []
  for x in xs:
    if p(x):
      t.append(x)
    else:
      f.append(x)
  return t, f

另一方面,如果我们的输入是一个多通的峰值,我们想要懒惰的输出,我们可以做这样的事情,请记住,这将两次迭代输入列表。

from itertools import filterfalse

def splitfilter_lazy(f, xs):
  return filter(f, xs), filterfalse(f, xs)

我怀疑这就是为什么没有提供。内置的大多数itertools功能(和MAP and filteritertools重要的很重要,可以包含在incoreins中)采取输入并以(懒惰)迭代器的形式产生输出,并且有了此功能,可以选择权衡:您是否想要急切的输出,但在该功能上只有一个迭代输入,还是您希望适当的迭代器作为输出,但要迫使输入是多通道?

This function is not built-in, to my knowledge. If we want to eagerly consume the input iterable and produce lists as output, then this is fairly straightforward to write.

def splitfilter(p, xs):
  t, f = [], []
  for x in xs:
    if p(x):
      t.append(x)
    else:
      f.append(x)
  return t, f

On the other hand, if our input is a multi-pass iterable and we want lazy output, we can do something like this, keeping in mind that this will iterate the input list twice.

from itertools import filterfalse

def splitfilter_lazy(f, xs):
  return filter(f, xs), filterfalse(f, xs)

I suspect that's exactly why it's not provided. Most of the built-in itertools functionality (and map and filter are itertools in spirit; they're just important enough to be included in builtins) take input and produce output in the form of (lazy) iterators, and with this function there's a choice of tradeoff: Do you want eager output but only one iteration on the input, or do you want proper iterators as output but to force the input to be multi-pass?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文