天天看点

学习13.内容# 1.内置函数二 # 2.闭包

学习13.内容# 1.内置函数二 # 2.闭包

目录

  • 内置函数二
  • 重要的内置函数和匿名函数
  • 闭包

内置函数二

abs 绝对值 返回的都是正数
print([abd(i) for i in lst])           
enumerate 枚举 ("可迭代对象","序号的起始值") 默认起始值是0
[(0,1),(1,2),(2,3)]
print([i for i in enumerate(lst,10)])

lst = [11,22,33,-44,23,21]
new_lst = []
for i in enumerate(lst):
    new_lst.append(i)
print(new_lst)

print([i for i in enumerate(lst,1000)])           
max 求最大值
print(max([1,2,3,4,56,7,8]))           
min 求最小值
print(min([1,2,3,4,-56,7,8]))           
sum 求和
print(sum([1,2,3,4,5],100))           
range
Python3.6:
    g = range(0,10)   # 可迭代对象
    g.__iter__()
Python2.6:
    range(0,10)       # 获取是一个列表
    xrange(0,10)      # 获取是一个可迭代对象
    
from collections import Iterable,Iterator
print(isinstance(g,Iterable))
print(isinstance(g,Iterator))           
sep多个元素的连接符
print(sep=" ", end="\n")
print(1, 2, 3, sep="      ")  # sep多个元素的连接符
print(1, end="\t")
print(2, end=" ")
print(3)           
open
print(12345,file=open("t1.txt","w",encoding="utf-8"))           
list,dict
print(list("alex")) #['alex',]
print(dict(key=1,a="alex"))

print(dict(((1,2),(2,3),(3,4))))
print(dict([i for i in enumerate(range(20),1)]))
           
zip拉链 按照最少的进行合并
lst1 = [1,2,3,4,5]
lst2 = ['a',"b","c","d","f","e"]
print(dict(list(zip(lst1,lst2))))  # 面试题
print(dict(zip(lst1,lst2)))  # 面试题
           
dir 查看当前函数的方法
print(dir(list))
           

重要的内置函数和匿名函数

匿名函数

f = lambda x,y:(x,y)
print(f(1,2))
print(f.__name__)

def func():
    return 1

print(func())

print((lambda x:x)(2)) # 同一行定义 同一行调用

lambda 关键字 -- 定义函数
x,y  形参
:x+y  返回值 -- 只能返回一个数据类型

lst = [lambda i:i*i for i in range(10)]
print(lst[2](2))

lst = []
for i in range(10):
    def func(i):
        return i*i
    lst.append(func)
print(lst[2](3))

lst = [lambda :i*i for i in range(10)]
print(lst[2]())

for i in range(10):
    pass
print(i)

lst = []
for i in range(10):
    def func():
        return i*i
    lst.append(func)
print(lst[2]())

一行函数
形参可以不写
返回值必须要写,返回值只能返回一个数据类型

lst = list((lambda i:i*i for i in range(5)))
print(lst[1](4))

lst = [x for x in (lambda :i**i for i in range(5))]
print(lst[2]())

lst1 = []
def func():
    for i in range(5):
        def foo():
            return i**i
        yield foo

for x in func():
    lst1.append(x)
print(lst1[2]())
           

format

print(format(13,">20"))  # 右对齐
print(format(13,"<20"))  # 左对齐
print(format(13,"^20"))  # 居中

# 进制转换
print(format(13,"08b"))    # 2
print(format(13,"08d"))    # 10
print(format(13,"08o"))    # 8
print(format(12,"08x"))    # 16

print(bin(13))
           

filter() 过滤

lst = [1,2,3,4,5,6,7]
def func(s):
    return s > 3
print(list(filter(func,lst)))
# func就是自己定义一个过滤条件,lst要迭代的对象
lst = [1,2,3,4,5,6,7]
print(list(filter(lambda x:x % 2 == 1,lst)))
           

map() # 对象映射

print(list(map(lambda x:x*x,[1,2,3,8,4,5])))
对可迭代对象中每个元素进行加工
           

reversed 反转

lst = [1,2,3,4,5]
    lst.reverse()
    print(lst)

    lst1 = list(reversed(lst))
    print(lst)
    print(lst1)
           

sorted 排序

lst = [1,23,34,4,5,213,123,41,12,32,1]
print(sorted(lst))   # 升序
print(lst)

lst = [1,23,34,4,5,213,123,41,12,32,1]
print(sorted(lst,reverse=True))  # 降序
           

key 制定排序规则

dic = {"key":1,"key1":2,"key3":56}
print(sorted(dic,key=lambda x:dic[x],reverse=True))  # key是指定排序规则

print(max([1,2,-33,4,5],key=abs))  # key指定查找最大值的规则
           

reduce 累计算

from functools import reduce
# reduce 累计算
print(reduce(lambda x,y:x-y,[1,2,3,4,5])
           

闭包

def func():
    a = 1
    def f1():
        def foo():
            print(a)
        return foo
    return f1
ret = func()
a = ret()
a()

func()()()
           

在嵌套函数内,使用非全局变量(且不是本层变量) -- 就是闭包

avg_lst = []
def func(pirce):
    avg_lst.append(pirce)
    avg = sum(avg_lst) / len(avg_lst)
    return avg
print(func(150000))
print(func(160000))
print(func(170000))
print(func(150000))
avg_lst.append(18888888)
           
def func(pirce):
    avg_lst = []
    avg_lst.append(pirce)
    avg = sum(avg_lst) / len(avg_lst)
    return avg
print(func(150000))
print(func(160000))
print(func(170000))
print(func(150000))
           
def func():
    avg_lst = []  # ***变量
    def foo(pirce):
        avg_lst.append(pirce)
        avg = sum(avg_lst) / len(avg_lst)
        return avg
    return foo
ret = func()()
           
print(ret(150000))
print(ret(160000))
print(ret(170000))
print(ret(150000))
print(ret(180000))
print(ret.__closure__)
(<cell at 0x0000018E93148588: list object at 0x0000018E931D9B08>,)
           

closure 判断是不是闭包

了解:
print(ret.__code__.co_freevars)  # 获取的是***变量
print(ret.__code__.co_varnames)  # 获取的是局部变量
           

闭包的作用

1.  保证数据的安全性
 2.  装饰器
           

posted on 2019-07-22 19:36 changxin7 阅读(...) 评论(...) 编辑 收藏