python - python 中的组合 filter() 无法按预期工作

标签 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']]

doc for generator expressions表示“不能在封闭范围内评估后续 for 子句和最左侧 for 子句中的任何过滤条件,因为它们可能依赖于从最左侧迭代获取的值。”。在您的情况下,过滤条件 if except_label ... 取决于从 for excex_label in ... 循环中获取的值。

关于python - python 中的组合 filter() 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55673872/

相关文章:

Python 在 Mac OS X 上诅咒鼠标事件

python - 2D 游戏中的运动(blitting 时的圆形位置?)

java - Chromium android 构建无效选项 --jarjar

python - 使用 Python 的 SCPClient 库在文件名中使用通配符

python - 计算S3存储桶内文件夹的大小

python - python kafka 库的编码/格式问题

python - 在 numpy 的范围内采样随机 float

python - Pycairo 比例失真

python - 在 Python 3.6 中计算多边形和 shapefile 之间的重叠

python - 从 Python 运行 MATLAB 脚本