filter函数内的函数参数求助!
Topic source看了函数返回那一章,终于懂了。这个感觉就是一个闭包吧,就是filter内的过滤函数不能引用后面会变的量,而是要把当前的量值存下来。像这样就可以:
def primes():
yield 2
it = _odd_iter() # 初始序列
while True:
n = next(it) # 返回序列的第一个数
yield n
it = filter(**lambda x, n=n: x % n**, it) # 构造新序列直接用匿名函数,但是需要把当前的变量n固定下来传入函数。
无法修改啊,上面那个回复本来想在最后一句的lambda函数那里加粗的,结果两边冒出来星号,我再贴一遍:
def primes():
yield 2
it = _odd_iter() # 初始序列
while True:
n = next(it) # 返回序列的第一个数
yield n
it = filter(lambda x, n=n: x % n, it) # 构造新序列直接用匿名函数,但是需要把当前的变量n固定下来传入函数。
def a(n): L=[n] k=list(map(str,L)) s=k[0] n=0 m=0 for i in range(len(s)//2): if s[i]==s[len(s)-1-i]: n=n+1 else: m=m+1 if n==(len(s)//2): return True else: return False
list(filter(a,list(range(10000))))
- 1
粥要新鲜的
这段代码,最后构造新序列时,为什么_not_divisible(n)不可以直接用匿名函数来写:lambda x: x%n>0?