据我了解,以下代码应输出[['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)
最佳答案
发生这种情况是因为 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']]
doc for generator expressions表示“不能在封闭范围内评估后续 for 子句和最左侧 for 子句中的任何过滤条件,因为它们可能依赖于从最左侧迭代获取的值。”。在您的情况下,过滤条件 if except_label ...
取决于从 for excex_label in ...
循环中获取的值。
关于python - python 中的组合 filter() 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55673872/