lambda x: x if x%2 else None
答案:
>>> def fun(x):
if x%2:
return x
else:
return None
答案:
#答案1
>>> list(filter(lambda x:x%3==0,range(1,101)))
#答案2
>>> list(filter(lambda x:not(x%3),range(1,101)))
答案:
#答案1:
>>> [i for i in range(1,101) if i%3==0]
#答案2:
>>> [i for i in range(1,101) if not(i%3)]
注:列表推导也叫列表解析,可以用来动态创建列表,语法:[关于i的表达式 for i in A],例子如下:
>>> [i*i for i in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> #上述代码分别打印了0-9各个数的平方,将其形成列表
>>> #以上代码可以解析为
>>> list1=[]
>>> for i in range(10):
list1.append(i*i)
>>> list1
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> list(zip([1,2,3,4,5,6],[1,2,3]))
[(1, 1), (2, 2), (3, 3)]
答案:
>>> list(map(lambda x,y:[x,y],[1,2,3,4,5,6],[1,2,3]))
[[1, 1], [2, 2], [3, 3]]
>>> def fun(n):
return lambda s:s*n
>>> num=fun(3)
>>> print(num(10));print('Love')
答案:
30
Love