匿名函数 - lambda 的应用

lambda 的高级应用:

 1 # ---CASE 1
 2 fs = map(lambda i:(lambda j: i*j), range(6))
 3 print([f(2) for f in fs])
 4 
 5 #---CASE 2
 6 fs = [lambda j:i*j for i in range(6)]
 7 print([f(2) for f in fs])
 8 
 9 #---CASE 3
10 fs = []
11 for i in range(6):
12     fs.append(lambda j:i*j)
13     if i==3:
14         break
15 print([f(2) for f in fs])
16 
17 #---CASE 4
18 fs = [(lambda i:lambda j:i*j)(i) for i in range(6)]
19 print([f(2) for f in fs])

[0, 2, 4, 6, 8, 10]
[10, 10, 10, 10, 10, 10]
[6, 6, 6, 6]
[0, 2, 4, 6, 8, 10]

参考:www.cnblogs.com/xiangnan/p/3900285.html?utm_source=tuicool&utm_medium=referral

-------------------------------------------------------------------------------------------------------

>>> L = [['a',1],['a',2],['a',4],['b',1],['b',2]];
>>> L
[['a', 1], ['a', 2], ['a', 4], ['b', 1], ['b', 2]]
>>> {key:[k[1] for k in L if k[0]==key] for key in set(j[0] for j in L)}
{'a': [1, 2, 4], 'b': [1, 2]}

posted @ 2018-03-06 17:38  Alice的小屋  阅读(216)  评论(0编辑  收藏  举报