python—07(函数的使用)

8:19 2019/1/14/周一
//匿名函数
res=lambda x:x+1//lambda是匿名函数的定义其中res接受的是地址。其中X表示的是输入值。
print(res(10))

//匿名函数里面是简单的语句,不能加复杂的逻辑结构。
把函数当成参数传递给另一个函数,如果没有返回值,则返回None .
返回值也可以是自己。

高阶函数:1。函数接收的值是函数
          2,返回值里面包含函数

//高级函数的使用。
 num=[1,2,3,4,5,6]
def add_one(x):
    return x+1
li=[]
def chang_num(add_one,num):
    for i in num:
         res =add_one(i)
         li.append(res)
    return li//这里面必须有返回值,不然打印出来的结果就是None.
print(chang_num(add_one,num))

结果:[2, 3, 4, 5, 6, 7]

//利用匿名函数同样可以实现对上面的操作:
num=[1,2,3,4,5,6]
def add_one(x):
    return x+1
li=[]
lambda x:x+1
def chang_num(add_one,num):
    for i in num:
         res =add_one(i)
         li.append(res)
    return li
print(chang_num(lambda x:x+1,num))

//输出结果:
[2, 3, 4, 5, 6, 7]

map 函数的使用
num=[1,2,3,4,5,6]
map(lambda x:x+1,num)
res=map(lambda x:x+1,num)
print(res)
结果<map object at 0x00A67270>//这里面输出的结果是地址,所以需要遍历打印里面的结果。

example:
num=[1,2,3,4,5,6]
map(lambda x:x+1,num)
res=map(lambda x:x+1,num)
print(res)
for i in res :
    print(i)
结果:
2
3
4
5
6
7

//加入list():
num=[1,2,3,4,5,6]
map(lambda x:x+1,num)
res=map(lambda x:x+1,num)
print(list(res))
结果:
[2, 3, 4, 5, 6, 7]

//startswith()用法。

li=("hao_anz","sb_yulis","sb_gaojun","cjm")
change_li=[]
for i in li:
    if not i.startswith('sb'):
        change_li.append(i)
print(change_li)
结果:['hao_anz', 'cjm']//打印的是列表。
//利用map()处理字符串返回的结果是True,False
li=("hao_anz","sb_yulis","sb_gaojun","cjm")
change_li=[]
for i in li:
    if not i.startswith('sb'):
        change_li.append(i)

print(change_li)
print(list(map(lambda x:x.startswith('sb'),li)))
结果:
['hao_anz', 'cjm']
[False, True, True, False]

//利用filter()函数也是打印出字符串里面的是正确的。
li=("hao_anz","sb_yulis","sb_gaojun","cjm")
change_li=[]
for i in li:
    if not i.startswith('sb'):
        change_li.append(i)

print(change_li)
res1=list(map(lambda x:x.startswith('sb'),li))
res2=list(filter(lambda x:x.startswith('sb'),li))
print(res1)
print(res2)

结果:
['hao_anz', 'cjm']
[False, True, True, False]
['sb_yulis', 'sb_gaojun']
//修改:
res3=list(filter(lambda x:not x.startswith('sb'),li))//在里面加一个lambda :后面的返回的值。
print(res3)
结果:['hao_anz', 'cjm']

//reduce()用法:

功能: 对一个序列进行压缩运算,得到一个值。但是reduce在python2的时候是内置函数,到了python3移到了functools模块,所以使用之前需要 from functools import reduce
调用: reduce(function,iterable),其中function必须传入两个参数,iterable可以是列表或者元组 
--------------------- 
from functools import reduce
y = [2,3,4,5,6]
reduce(lambda x,y: x + y,y)
print(reduce(lambda x,y: x -y,y))
结果:-16

from functools import reduce
print(reduce(lambda x, y: x + y, range (100), 10))//10表示的是初始值。reduce 就是把所有的值合并成一个值。

结果:4960
//decode 是解码方式()里面加入的是解码规则。
res="1230"
print(res.encode().decode("gbk"))

猜你喜欢

转载自blog.csdn.net/qq_37431752/article/details/86487167