首页 > 解决方案 > python中的组合过滤器()不能按预期工作

问题描述

据我了解,以下代码应输出[['b']]。相反,它输出[['a', 'exclude'], ['b']].

这是python中的错误,还是我误解了什么?

lists_to_filter = [
    ['a', 'exclude'],
    ['b']
]
# notice that when 'exclude' is the last element, the code returns the expected result
for exclude_label in ['exclude', 'something']:
    lists_to_filter = (labels_list for labels_list in lists_to_filter if exclude_label not in labels_list)
    # notice that changing the line above to the commented line below (i.e. expanding the generator to a list) 
    # will make the code output the expected result, 
    # i.e. the issue is only when using filter on another filter, and not on a list
    # lists_to_filter = [labels_list for labels_list in lists_to_filter if exclude_label not in labels_list]
lists_to_filter = list(lists_to_filter)
print(lists_to_filter)

标签: python

解决方案


发生这种情况是因为lists_of_filter仅在循环外迭代。在你拥有的循环之外exclude_label == 'something',这就是你得到意想不到的结果的原因。要检查它,您可以输入一行exclude_label = 'exclude'

lists_to_filter = [
    ['a', 'exclude'],
    ['b']
]

for exclude_label in ['exclude', 'something']:
    lists_to_filter = (labels_list for labels_list in lists_to_filter if exclude_label not in labels_list)

exclude_label = 'exclude'
lists_to_filter = list(lists_to_filter)
print(lists_to_filter)  # [['b']]

生成器表达式的文档说“后续的 for 子句和最左边的 for 子句中的任何过滤条件都不能在封闭范围内进行评估,因为它们可能取决于从最左边的可迭代对象获得的值。 ”。在您的情况下,过滤条件if exclude_label ...取决于从for exclude_label in ...循环获得的值。


推荐阅读