1.函数的参数传递
def test_fun(a, b = 6, *c, **d):#一个*号是元组,两个*是字典
print("a =", a, ",b =", b, ",c =", c, ", d =",d)
test_fun(1)
a = 1 ,b = 6 ,c = () , d = {}
test_fun(1,2)
a = 1 ,b = 2 ,c = () , d = {}
test_fun(1, 2, 3)
a = 1 ,b = 2 ,c = (3,) , d = {}
test_fun(1,2,3,4)
a = 1 ,b = 2 ,c = (3,) , d = {}
test_fun(1,2,3,4)
a = 1 ,b = 2 ,c = (3, 4) , d = {}
test_fun(a = 1)
a = 1 ,b = 6 ,c = () , d = {}
test_fun(a = 1, b = 2)
a = 1 ,b = 2 ,c = () , d = {}
test_fun(a = 1, b = 2, c = 3)
a = 1 ,b = 2 ,c = () , d = {'c': 3}
test_fun(1, b = 2)
a = 1 ,b = 2 ,c = () , d = {}
test_fun(1,2,3,4, x = 1)
a = 1 ,b = 2 ,c = (3, 4) , d = {'x': 1}
test_fun(1,2,3,4,5,6, x = 1,y = 2,z = 3)
a = 1 ,b = 2 ,c = (3, 4, 5, 6) , d = {'x': 1, 'y': 2, 'z': 3}
2.函数文档
3.lambda匿名函数
f = lambda x: x+5
f(3)
8
sorted(['abc', ‘afe', ‘acb']
key=lambda x:(x[0],x[2]))
print(key)
['acb','abc','afe']
4.map/filter/zip/reduce/enumerate map函数
map函数
def square(x):
return x ** 2
map(square, [1, 2, 3, 4, 5])
<map at 0x26ddf18e9b0>
def square(x):
return x ** 2
list(map(square, [1, 2, 3, 4, 5]))
[1, 4, 9, 16, 25]
map(lambda x: x**2,[1,2,3,4,5])
<map at 0x26ddf18e7f0>
map(lambda x, y:x + y,[1,3,5,7,9], [2,4,6,8,10])
<map at 0x26ddf18e240>
list(map(lambda x, y:x + y,[1,3,5,7,9], [2,4,6,8,10]))
[3, 7, 11, 15, 19]
def add(x,y,z):
return x + y + z
list1 = [1,2,3]
list2 = [1,2,3,4,]
list3 = [1,2,3,4,5]
res = map(add, list1,list2,list3)
print(list(res)) #3个参数长度不同时,按最短的来算
[3, 6, 9]
list(map(str,[1,2,3]))
['1', '2', '3']
str(0)
'0'
x,y,z = map(str,range(3))
y
'1'
filter函数
def is_odd(n):
return n % 2 == 1
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(newlist)
<filter object at 0x0000000005815CC0>
def is_odd(n):
return n % 2 == 1
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(list(newlist))
[1, 3, 5, 7, 9]
zip函数
a = [1,2,3]
b = [4,5,6]
zip(a,b)
<zip at 0x26ddf184908>
a = [1,2,3]
b = [4,5,6]
list(zip(a,b))
[(1, 4), (2, 5), (3, 6)]
a = [1,2,3]
b = [4,5,6]
zipped = zip(a,b)
list(zip(*zipped))
[(1, 2, 3), (4, 5, 6)]
dict(zip([1,2],[3,4]))
{1: 3, 2: 4}
enumerate函数
seasons = ['spring', 'summer', 'fall', 'winter']
list(enumerate(seasons))
[(0, 'spring'), (1, 'summer'), (2, 'fall'), (3, 'winter')]
list(enumerate(seasons, start = 1))
[(1, 'spring'), (2, 'summer'), (3, 'fall'), (4, 'winter')]