Two built-in functions
abs () - absolute value
the enumerate ( "iterables" number starting value (default 0)) to give the tuple enumeration ---
lst = [1,2,3,4,5,7,8,9] print([i for i in enumerate(lst)]) 结果: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 7), (6, 8), (7, 9)]
max (iterables) selecting the maximum value ---
print(max([1,2,-33,4,5],key=abs)) 结果: -33
min (iterables) minimum ---
sum (digital element iterable, initial value) - summation
open()
range () iterables python 2 in range () Gets a list of objects iteration time xrange
print (sep = "a plurality of connector elements", end = "\ n", file = open ( "t1.txt", "w", encoding = "utf-8")
''' 源码分析 def print(self, *args, sep=' ', end='\n', file=None): # known special case of print """ print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) file: 默认是输出到屏幕,如果设置为文件句柄,输出到文件 sep: 打印多个值之间的分隔符,默认为空格 end: 每一次打印的结尾,默认为换行符 flush: 立即把内容输出到流文件,不作缓存 """ '''
len () required length - the common module
list("alex") ---["a","l","e","x"]
dict() dict(((1,2))) ={1,2}
dic = dict(key =1,a ="A") print(dic) 结果: {'key': 1, 'a': 'A'} lst = [i for i in enumerate(range(20))] print(dict(lst)) 结果: {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14, 15: 15, 16: 16, 17: 17, 18: 18, 19: 19}
tuple
type
list (zip (iterables, iterables)) to index the fastener pair are combined according to a minimum,
zip function for an object as a parameter to be iterative, the corresponding element of the object packed into a tuple, and return the contents of these tuples composition, if the number of elements of each iterator inconsistent, returns the length of the shortest length ,
lst1 = [1,2,3,4,5] lst2 = ["a","b","c","d","e","f","g"] lst3 = ["akex","wer","你","好"] print(zip(lst1,lst2)) print(list(zip(lst1,lst2))) print(list(zip(lst1,lst2,lst3))) print(dict(list(zip(lst1,lst2)))) print(dict(zip(lst1,lst2))) 结果: <zip object at 0x000001A4C45C6548> [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')] [(1, 'a', 'akex'), (2, 'b', 'wer'), (3, 'c', '你'), (4, 'd', '好')] {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'} {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
dir (list) view the current function method
Important built-in functions and anonymous functions
Anonymous lambda function equivalent to def
The name of the anonymous function is lambda
Anonymous function parameter can not write, but must have a return value
Anonymous function no matter how complicated can only write a single line. And return directly after the end of the logical data
f = lambda x,y :x+y
print(f(1,2))
print(f.__name__()) <lambda>
#lambda:关键字 --定义函数
#x,y---形参
#:x+y ---返回值--只能返回一个元素
print(lambda x:x)
print(lambda x:x(2))
print((lambda x:x)(2))
结果:
<function <lambda> at 0x0000021D2C401EA0>
<function <lambda> at 0x0000021D2C401EA0>
2
lst = []
for i in range(10):
def func():
return i*i
lst.append(func)
print(lst[2]())
结果
81
lst = [lambda i: i*i for i in range(10)]
print(lst[2](2))
lst = [lambda : i*i for i in range(10)]
print(lst[2]())
结果:
4
8
print((lambda i: i*i for i in range(10)))
print(list((lambda i: i*i for i in range(5))))
lst = list((lambda i: i*i for i in range(5)))
print(lst[2](4))
结果:
<generator object <genexpr> at 0x000001936D934C50>
[<function <genexpr>.<lambda> at 0x000001936D7F1EA0>, <function <genexpr>.<lambda> at 0x000001936D9CDA60>, <function <genexpr>.<lambda> at 0x000001936D9CDAE8>, <function <genexpr>.<lambda> at 0x000001936D9CDB70>, <function <genexpr>.<lambda> at 0x000001936D9CDBF8>]
16
lst = [x for x in (lambda :i**i for i in range(5))]
print(lst[1]())
结果:
256
Built-in functions
format() 08b--2 08d --10 08o --8 08x--16
print(format(13,">20"))右对齐 print(format(13,"<20"))左对齐 print(format(13,"^20"))居中 print(format(13,"b")) print(format(13,"08b"))#二进制 print(format(13,"08d"))#十进制 print(format(13,"08o"))#八进制 print(format(13,"08x"))#十六进制 结果: 1101 00001101 00000013 00000015 0000000d
filter (filter function (specifying filtering criteria), iterables) - Filter filter + lambda often test
语法: filter(function,iterable) function: 用来筛选的函数,在filter中会自动的把iterable中的元素传递给function,然后根据function返回的True或者False来判断是否保留此项数据 iterable:可迭代对象 lst = [{'id':1,'name':'alex','age':18}, {'id':1,'name':'wusir','age':17}, {'id':1,'name':'taibai','age':16},] ls = filter(lambda e:e['age'] > 16,lst) print(list(ls)) 结果: [{'id': 1, 'name': 'alex', 'age': 18}, {'id': 1, 'name': 'wusir', 'age': 17}] lst = [1,2,3,4,5,6,7] def func(s): return s>3 print(filter(func,lst)) print(list(filter(func,lst)))#func自己定义的过滤函数,lst要迭代的对相 结果: <filter object at 0x000001B46B96A940> [4, 5, 6, 7] lst = [1,2,3,4,5,6,7] print(filter(lambda x :x>3,lst)) print(list(filter(lambda x :x>3,lst))) print(list(filter(lambda x :x % 2 == 1,lst))) 结果: <filter object at 0x000002D8EFD9A8D0> [4, 5, 6, 7] [1, 3, 5, 7
map (function, iterables) # --- object mapping object for each iteration may be processed element
映射函数 语法: map(function,iterable) 可以对可迭代对象中的每一个元素进映射,分别取执行function print(map(lambda x:x+1,[1,2,3,4,5])) print(list(map(lambda x:x+1,[1,2,3,4,5]))) print(list(map(lambda x:x**x,[1,2,3,4,5]))) 结果: <map object at 0x000001F01B15A908> [2, 3, 4, 5, 6] [1, 4, 27, 256, 3125]
revesed (string \ lists \ tuples, key = abs) - to be ordered iteration of objects and collections can not enjoy tiles dictionary
print(reversed("alex")) print(list(reversed("alex"))) lst = [1,2,3,4,5] lst1 = list(reversed(lst)) print(lst1) print(lst) 结果: <reversed object at 0x0000028C0409A8D0> ['x', 'e', 'l', 'a'] [5, 4, 3, 2, 1] [1, 2, 3, 4, 5] dic = {"key":1,"key1":2,"key3":3} print(sorted(dic ,key = lambda x:dic[x],reverse=True)) 结果: ['key3', 'key1', 'key']
sorted ( "iterable", key = function names --- specify a collation, reverse = True (default ascending, descending wrote is True))
语法:sorted(iterable,key=None,reverse=False) iterable : 可迭代对象 key: 排序规则(排序函数),在sorted内部会将可迭代对象中的每一个元素传递给这个函数的参数.根据函数运算的结果进行排序 reverse :是否是倒序,True 倒序 False 正序 lst = [1,2,4165,65,5,465,465,5,46,465,6,416,5,123,12,1] print(sorted(lst))#经过排序的新列表 print(lst)#原列表不会改变 结果: [1, 1, 2, 5, 5, 5, 6, 12, 46, 65, 123, 416, 465, 465, 465, 4165] [1, 2, 4165, 65, 5, 465, 465, 5, 46, 465, 6, 416, 5, 123, 12, 1] lst = [1,2,4165,65,5,465,465,5,46,465,6,416,5,123,12,1] print(sorted(lst,reverse=True)) print(lst) 结果: [4165, 465, 465, 465, 416, 123, 65, 46, 12, 6, 5, 5, 5, 2, 1, 1] [1, 2, 4165, 65, 5, 465, 465, 5, 46, 465, 6, 416, 5, 123, 12, 1]
reduce (Function - Specifies calculation tired, iterables) with the accumulated calculation using lambda
from functools import reduce def func(x,y): return x + y # reduce 的使用方式: # reduce(函数名,可迭代对象) # 这两个参数必须都要有,缺一个不行 ret = reduce(func,[3,4,5,6,7]) print(ret) # 结果 25 reduce的作用是先把列表中的前俩个元素取出计算出一个值然后临时保存着, 接下来用这个临时保存的值和列表中第三个元素进行计算,求出一个新的值将最开始 临时保存的值覆盖掉,然后在用这个新的临时值和列表中第四个元素计算.依次类推 注意:我们放进去的可迭代对象没有更改 以上这个例子我们使用sum就可以完全的实现了.我现在有[1,2,3,4]想让列表中的数变成1234,就要用到reduce了. 普通函数版 from functools import reduce def func(x,y): return x * 10 + y # 第一次的时候 x是1 y是2 x乘以10就是10,然后加上y也就是2最终结果是12然后临时存储起来了 # 第二次的时候x是临时存储的值12 x乘以10就是 120 然后加上y也就是3最终结果是123临时存储起来了 # 第三次的时候x是临时存储的值123 x乘以10就是 1230 然后加上y也就是4最终结果是1234然后返回了 l = reduce(func,[1,2,3,4]) print(l) 匿名函数版 l = reduce(lambda x,y:x*10+y,[1,2,3,4]) print(l) 在Python2.x版本中recude是直接 import就可以的, Python3.x版本中需要从functools这个包中导入 龟叔本打算将 lambda 和 reduce 都从全局名字空间都移除, 舆论说龟叔不喜欢lambda 和 reduce 最后lambda没删除是因为和一个人给龟叔写了好多封,进行交流然后把lambda保住了. from functools import reduce print(reduce(lambda x,y:x+y,[1,2,3])) print(reduce(lambda x,y:x*y,[1,2,3,4,5])) print(reduce(lambda x,y:x-y,[1,2,3,4,5])) 结果: 6 120 -13
Closure:
1. In the nested functions, global variables would not be a non-variable layer is present - that is, closure
Essence to ensure the security of data (purity degree), decorators: the role of
def func():
a = 1 #自由变量
def foo():
print(a)
return foo
ret = func()
ret()
def foo():
avg_lst = []
def func(price):
avg_lst.append(price)
avg = sum(avg_lst)/len(avg_lst)
return avg
return func
ret = foo()
print(ret.__closure__)#判断是否是闭包
print(foo.__closure__)
了解:
print(ret.__code__.co_freevars)#获取的是自由变量
print(ret.__code__.co_varnames)#获取局部变量
结果:
(<cell at 0x000002152DF07618: list object at 0x000002152DED3948>,)
None
('avg_lst',)
('price', 'avg')