简约不简单的匿名函数
672
1
d = {'mike': 10, 'lucy': 2, 'ben': 30}
a = sorted(d.items(), key = lambda x:x[1], reverse = True)
print(a)
[collapse title="截图" status="false"]
[/collapse]
[collapse title="代码块" status="false"]
#!/usr/bin/env python
# coding: utf-8
# In[2]:
[(lambda x:x*x)(x) for x in range(10)]
# In[7]:
l = [(1, 20), (3,0), (9, 10), (2, -1)]
l.sort(key = lambda x:x[1]) #根据列表中元组的第二个元素排序
print(l)
# In[11]:
squared = map(lambda x: x**2, [1, 2, 3, 4, 5])
# 函数 map(function, iterable) 的第一个参数是函数对象,第二个参数是一个可以遍历的集合,
# 它表示对 iterable 的每一个元素,都运用 function 这个函数
# In[14]:
def multiply_2(l):
for index in range(0, len(l)):
l[index] *= 2
return l
l = [1, 2, 3]
multiply_2(l)
print(l)
# In[24]:
def multiply_2_pure(l):
new_list = []
for item in l:
new_list.append(item * 2)
print(new_list)
l = [1, 2, 3]
multiply_2_pure(l)
print(l)
# In[19]:
l = [1, 2, 3, 4, 5]
new_list = map(lambda x: x * 2, l)
print(new_list)
# In[25]:
d = {'mike': 10, 'lucy': 2, 'ben': 30}
a = sorted(d.items(), key = lambda x:x[1], reverse = True)
print(a)
# In[29]:
from functools import reduce
l = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, l) # 1*2*3*4*5 = 120
print(product)
[/collapse]