python - 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)
解决方案
发生这种情况是因为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 ...
循环获得的值。
推荐阅读
- sql - PL/SQL Developer 看不到插入语句的结果
- csv - Apache Spark - 速度故障 read.csv()
- amazon-web-services - AWS 代码工件策略权限无效
- github - Google Cloud Build/GitHub 中的无效参数错误
- javascript - 是否可以在云函数中使用带有通配符的 startWith?
- python - MNIST 上的 PCA 有效,但验证数据的表现非常糟糕
- python - pandas loc 属性的行为与预期不同
- python - 使用 Selenium 搜索元素时指定了非法选择器或找不到 xpath 错误
- javascript - 转换后如何解决上行文本问题 - svg
- mysql - 按在 SQL 中保存为字符串的日期过滤