用元组过滤和拆包处理空箱 [英] Handling empty case with tuple filtering and unpacking

查看:47
本文介绍了用元组过滤和拆包处理空箱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些并行列表,需要根据其中一个列表中的值进行过滤的情况.有时候我写这样的东西来过滤它们:

I have a situation with some parallel lists that need to be filtered based on the values in one of the lists. Sometimes I write something like this to filter them:

lista = [1, 2, 3]
listb = [7, 8, 9]
filtered_a, filtered_b = zip(*[(a, b) for (a, b) in zip(lista, listb) if a < 3])

这给出了 filtered_a ==(1,2) filtered_b ==(7,8)

但是,将最终条件从 a<3 a<0 导致引发异常:

However, changing the final condition from a < 3 to a < 0 causes an exception to be raised:

Traceback (most recent call last):
  ...
ValueError: need more than 0 values to unpack

我知道为什么会这样:列表理解为空,所以就像调用 zip(* []),就像 zip()一样,返回一个空列表,该列表无法解压缩到单独的filtered_a和filtered_b可迭代对象中.

I know why this is happening: the list comprehension is empty, so it's like calling zip(*[]), which is like zip(), which just returns an empty list which cannot be unpacked into separate filtered_a and filtered_b iterables.

是否有一个更好的(更短,更简单,更pythonic的)过滤函数来处理空情况?在空的情况下,我希望filtered_a和filtered_b是空的可迭代对象,因此以下任何代码都可以保持不变.

Is there a better (shorter, simpler, more pythonic) filtering function that handles the empty case? In the empty case, I would expect filtered_a, and filtered_b to be empty iterables so any following code could remain unchanged.

推荐答案

您可以使用默认值简单地短路:

You could simply short-circuit with the default values:

filtered_a, filtered_b = zip(*[(a, b) for a, b in zip(lista, listb) if a < 0]) or ([], [])
print(filtered_b, filtered_a)
# [] []

对于Python 3,您需要在 zip 返回的迭代器上调用 list ,以便可以将第一个操作数评估为空列表(而不是迭代器),否则即使迭代器可能为空,也不会达到默认值,因为 bool(iter([])) True .

For Python 3, you'll need to call list on the iterator returned by zip so the first operand can be evaluated as an empty list (not an iterator), else the default value is never reached even when the iterator is potentially empty since bool(iter([])) is True.

这篇关于用元组过滤和拆包处理空箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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