双重理解的 Pythonic 方式

Pythonic way to a double comprehension

我必须从图中获取句柄和标签列表,标签为“True”或“False”的情况除外。以下代码完成此操作:

# h, l = [a for a in ax.get_legend_handles_labels()] #redundant
h, l = ax.get_legend_handles_labels()
handles = [a for a, b in zip(h, l) if (b != 'True' and b != 'False')]
labels = [b for a, b in zip(h, l) if (b != 'True' and b != 'False')]

尽管如此,这似乎完全“不是pythonic”。有没有更优雅的方法来解决这个问题? 我尝试了以下 2-liner 但我在第 2 行得到了 ValueError: too many values to unpack (expected 2):

h, l = [a for a in ax.get_legend_handles_labels()]
handles, labels = [(a,b) for a, b in zip(h, l) if (b != 'True' and b != 'False')]

我希望 Python 有一个在线解决方案...有吗?

为了可重复性:

(h,l)=(['handle1','handle2', 'handle3'],['label1','True', 'False'])
handles = [a for a, b in zip(h, l) if (b != 'True' and b != 'False')]
labels = [b for a, b in zip(h, l) if (b != 'True' and b != 'False')]

此可重现示例的预期输出是

handles=['handle1'] 
labels=['label1']

您可以再次使用 zip:

h, l = [a for a in ax.get_legend_handles_labels()]
filtered_hl = [(a,b) for a, b in zip(h, l) if (b != 'True' and b != 'False')]
handles, labels = map(list, zip(*filtered_hl))

有一种称为“解压缩”迭代器的技术(参见我的代码示例中的第四行),这是一种嵌套元素的重塑。如果您熟悉它,它有点像 numpy 的 swapaxes。组合 python 的迭代器 zipfilter 您可以通过以下方式实现所需的行为:

h, l = ax.get_legend_handles_labels()
zipped = zip(h, l)
filtered = filter(lambda t: t[1] != 'True' and t[1] != 'False', zipped)
handles, labels = zip(*filtered)