1.请利用filter()过滤出1~100中平方根是整数的数,即结果应该是:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
2.列表按照其中每一个值的绝对值排序
li = [1,-2,3,-48,78,9]
3.列表按照每一个元素的len排序
li = [(1,-2),[3],[-48,78,9],'hello world']
4.请把以下函数变成匿名函数
def add(x,y): return x+y
5.下面程序的输出结果是:
d = lambda p:p*2t = lambda p:p*3x = 2x = d(x)x = t(x)x = d(x)print (x)6.现有两元组(('a'),('b')),(('c'),('d')),请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}]
# 看到匿名函数,就要想到肯定会带着考内置函数,而和匿名函数相关的内置函数只有5个:min max filter map sorted
# 排除法想到map# 没用匿名函数7.以下代码的输出是什么?请给出答案并解释。
def multipliers(): return [lambda x:i*x for i in range(4)]print([m(2) for m in multipliers()])
ANS:
#1import mathli=[]def f(x): return math.sqrt(x)==int(math.sqrt(x))s=list(filter(f,range(101)))
#2li = [1,-2,3,-48,78,9]l=sorted(li,key=abs)
#3li = [(1,-2),[3],[-48,78,9],'hello world']l=sorted(li,key=len)print(l)
#4f=lambda x,y:x+y
#524
#6#方法一l=lambda x,y:[{x[0]:y[0]},{x[1]:y[1]}]#方法二tu1 =(('a'),('b'))tu2 =(('c'),('d'))res = zip(tu1,tu2)# def func(tup):# return {tup[0]:tup[1]}ret = map(lambda tup:{tup[0]:tup[1]},res)# for i in ret:# print(i)print(list(ret))#简化版print(list(map(lambda tup:{tup[0]:tup[1]},zip((('a'),('b')),(('c'),('d'))))))
#7[6,6,6,6]def multipliers(): return (lambda x:i*x for i in range(4)) # 改为生成器print([m(2) for m in multipliers()])