sonichuang 发表于 2018-6-2 16:57:22

关于filter函数

下面第一种情况为什么不能用列表显示出来呢?x % 2 不能算做一个函数吗?用filter返回的都是一个对象的地址对吗?要怎么做才能让第一种情况的对象显示出来呢?
1.
>>> filter(x % 2, range(10))
<filter object at 0x109e414a8>
>>> list(filter(x % 2, range(10)))
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: 'int' object is not callable

2.
>>> filter(lambda x: x%2, range(10))
<filter object at 0x10add62e8>
>>> list(filter(lambda x: x%2, range(10)))

冬雪雪冬 发表于 2018-6-3 16:57:32

x % 2 是表达式,不是函数。filter的参数需要函数和一个序列

sonichuang 发表于 2018-6-3 17:18:49

冬雪雪冬 发表于 2018-6-3 16:57
x % 2 是表达式,不是函数。filter的参数需要函数和一个序列

但为什么没有报错呢?而是返回一个地址

冬雪雪冬 发表于 2018-6-3 17:21:22

sonichuang 发表于 2018-6-3 17:18
但为什么没有报错呢?而是返回一个地址

你在前面一定给x赋值过,不如就会报错。
>>> filter(x % 2, range(10))
Traceback (most recent call last):
File "<pyshell#177>", line 1, in <module>
    filter(x % 2, range(10))
NameError: name 'x' is not defined
页: [1]
查看完整版本: 关于filter函数