Python filter()用法的差异

Python filter()用法的差异,python,python-3.x,filter,Python,Python 3.x,Filter,我发现,filter(function,iterable)不再返回列表,而是返回iterable filter对象(对于python3)。它必须转换成如下列表:list(filter(find_first,groups))。我还希望在传递给函数之前,先计算参数 我发现了filter()的奇怪行为,我不理解: # scale_groups is of type list res = filter(find_first, scale_groups) first = list(res) res2 =

我发现,
filter(function,iterable)
不再返回列表,而是返回iterable filter对象(对于python3)。它必须转换成如下列表:
list(filter(find_first,groups))
。我还希望在传递给函数之前,先计算参数

我发现了
filter()
的奇怪行为,我不理解:

# scale_groups is of type list
res = filter(find_first, scale_groups)
first = list(res)
res2 = list(filter(find_first, scale_groups))
我希望
first
res2
包含相同的元素,但是
first
空列表
res2
包含预期的一个元素

def get_first_scale_group_by_name(self, name):
    scale_groups = self.as_client.describe_auto_scaling_groups()['AutoScalingGroups']

    def find_first(group):
        return group['AutoScalingGroupName'].startswith(name)
    res = filter(find_first, scale_groups)
    res2 = list(filter(find_first, scale_groups))
    first = list(res)
    return first

您没有正确使用筛选器。find_first方法中的“name”在运行时可能会任意更改,从而导致问题。此外,您应该将其更改为包含我们检查的一些数据,以便我们可以自己复制它为什么不正确?这是一个闭包,它将使用调用时链接的名称
find\u first
。此外部名称变量将作为
get\u first\u scale\u group\u by\u name
的名称参数。而且这个参数不能随意更改,不是吗?更糟糕的是,这样做的方式不好,因为不知道它的人可能会意外地破坏你的代码,因为它没有明显的相关性。当使用你的代码和一些虚拟值进行
缩放组时,我无法重现你的结果。你确定没有别的事情发生吗?您是否有可能拥有一个展示奇怪的
filter
行为的自包含示例?