Built-in functions supplement, anonymous functions and closures

Built-in functions, anonymous functions and closures

Anonymous function

def func(x,y):
    return (x,y)
print(func(1,2))
# 结果:
(1,2)

f = lambda x,y:(x,y)  # lambda关键字
print(f(1,2))
# 结果:
(1,2)

print((lambda x,y:(x,y))(1,2))
# 结果:
(1,2)               # 一行代码实现匿名函数的定义及调用

print(lambda :1)
print((lambda :1)())       # 匿名函数可以不写参数,但必须具有返回值,返回值必须为一个,可以是任意数据类型
# 结果:
<function <lambda> at 0x000001C2089A6048>    # 打印函数名,即函数内存地址
1             # 调用函数,打印函数值

Built-in functions

  • ABS () the absolute value function

    print(abs(-2)) #结果:2
    lst = [1,2,4,6,-6,-4,4]
    print(abs(i) for i in lst)   #结果:<generator object <genexpr> at 0x000001CD1A64DF10> 生成器内存地址
    print([abs(i) for i in lst])  #结果:[1, 2, 4, 6, 6, 4, 4]
  • enumerate (iterables, initial value)

    lst = [1,31,64,64,75]
    print([i for i in enumerate(lst,1)]) #默认初始值为0,指定为1
    # 结果:
    [(1, 1), (2, 31), (3, 64), (4, 64), (5, 75)]
  • print () screen output file output

    print(1,2,3,sep='*',end='\t')   # sep指定间隔方式,end指定结束方式
    print(1)
    # 结果:1*2*3    1   
    print(12345,file=open('t1.txt','w',encoding='utf-8') )
  • list () will be converted into a list iterable

  • tuple () will be converted into a iterable tuple

  • dict () to create a dictionary corresponding way.

  • sum () sums

    print(sum([1,2,3]))
    print(sum((1,2,3),100))
  • max () selecting the maximum value

    print(max([1,6,12,7,432,3,-33]))  #返回列表元素的最大值
    print(max([1,4,23,-56,42,7],key=abs)) #返回列表元素绝对值的最大值
    dic = {'a':3,'b':2,'c':1}
    print(max(dic,key=lambda x:dic[x])) #按照字典的值进行比较,返回值最大的键
  • min () for the minimum (and the same method of selecting the maximum value)

  • the reversed () inverted sequence

    l = reversed('你好')  # l 获取到的是一个生成器
    print(list(l))
    ret = reversed([1, 4, 3, 7, 9])
    print(list(ret))  # [9, 7, 3, 4, 1]
  • zip () function fastener

    lst1 = [1,2,3]
    lst2 = ['a','b','c','d']
    lst3 = (11,12,13,14,15)
    for i in zip(lst1,lst2,lst3):
        print(i)
    结果:
    (1, 'a', 11)
    (2, 'b', 12)
    (3, 'c', 13)
  • filter (a filter, iterables)

    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)))
    # 以列表形式返回列表元素中为奇数的元素
  • sorted (iterables, collation, ascending descending)

    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))  # 降序
    
    dic = {"key":1,"key1":2,"key3":56}
    print(sorted(dic,key=lambda x:dic[x],reverse=True))  # key是指定排序规则
  • format()

    print(format(13,">20"))  # 右对齐
    print(format(13,"<20"))  # 左对齐
    print(format(13,"^20"))  # 居中
    
    print(format(13,"08b"))    # 8位二进制
    print(format(13,"08d"))    # 8位十进制值
    print(format(13,"08o"))    # 8位八进制
    print(format(12,"08x"))    # 8位十六进制
  • map () map

    map() # 对象映射
    print(list(map(lambda x:x*x,[1,2,3,8,4,5])))
    # 结果:
    [1, 4, 9, 64, 16, 25]
    # 对可迭代对象中每个元素进行加工
  • the reduce ( "function", "iterables") totalizer

    from functools import reduce
    print(reduce(lambda x,y:x-y,[1,2,3,4,5]))
    # 结果:-13

Closure

Closure: the nested function, a global variable is a non-closure

Closure of the benefits:

Data security, decorative uses

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>
    
# 了解:
# print(ret.__code__.co_freevars)  # 获取的是自由变量
# print(ret.__code__.co_varnames)  # 获取的是局部变量

Guess you like

Origin www.cnblogs.com/lifangzheng/p/11229543.html