官方网站:https://docs.python.org/3/library/functions.html?highlight=built
1 函数的程序
2
3
4
5 print( all([1,-5,3]) ) #如果列表全部为真则返回true
6
7
8
9 print( any([]) ) #只要有一个真就返回true
10
11
12
13 a = ascii([6,7,"信吧信吧"]) #把一个内存数据对象变成字符串形式
14 print(type(a),[a])
15
16
17
18 print(bool(1)) #bool函数判断真假
19
20
21
22 a = bytes("abcde",encoding="utf-8")
23 print(a) #输出 b'abcde'
24 print(a.capitalize(),a) # 输出 b'Abcde' b'abcde'
25
26
27
28 b = bytearray("abcde",encoding="utf-8") #把二进制当成数组可修改,改二进制
29 print( b[1] ) #输出是ascii码 98
30 b[1]= 50
31 print(b) # bytearray(b'a2cde')
32
33
34
35 print(chr(55)) # 输出7,返回数字所对应的ascii码
36 print(ord('7')) # 输出55 , 返回ascii码所对应的数字
37
38
39
40 def sayhi():pass
41 print( callable(sayhi) ) #callable是否可以调用,后面可以加括号就可以调用,函数等
42
43
44
45
46 code = '''
47 def fib(max): #10
48 n, a, b = 0, 0, 1
49 while n < max:
50 yield b
51 a, b = b, a + b
52 n = n + 1
53 return '---done---'
54
55 g = fib(6)
56 while True:
57 try:
58 x = next(g)
59 print('g:', x)
60 except StopIteration as e:
61 print('Generator return value:', e.value)
62 break
63 '''
64 py_obj = compile(code,"","exec") #将字符串变成执行代码
65 exec(py_obj)
66 exec(code)
67
68
69
70 a = ()
71 print(dir(a)) #查看a字典有什么方法
72
73
74
75 (lambda n:print(n))(5) #匿名函数第一种
76 calc = lambda n:3 if n<4 else n #匿名函数的三元运算
77 print(calc(2))
78
79
80
81 res = filter(lambda n:n>5,range(10)) #还没搞明白
82 res = map(lambda n:n*2,range(10))
83 res = [ lambda i:i*2 for i in range(10)]
84 import functools
85 res = functools.reduce( lambda x,y:x*y,range(1,10 ))# print(res )
86
87
88
89 a = frozenset([1,4,333,212,33,33,12,4]) #定义不可变列表
90
91
92
93 print(globals()) #返回整个程序所有变量
94
95
96
97 print(hex(255)) #转出16进制
98 print(bin(255)) #将数字转化为二进制
99 print(oct(17)) #将数字转化为8进制
100 print(pow(2,8)) #算出2的8次方
101
102
103
104 def test():
105 local_var =333
106 print(locals())
107 print(globals())
108 test()
109 print(globals())
110 print(globals().get('local_var')) #抓出变量的值
111
112
113
114 print(round(1.22235,3) )#保留小数位数
115
116
117
118 a = {6:2,8:0,1:4,-5:6,99:11,4:22} #字典是无序的,要使他有序,就是排序
119 print( sorted(a) ) #[-5, 1, 4, 6, 8, 99] 把key排序了,默认是用key排序
120 print( sorted(a.items()) ) #[(-5, 6), (1, 4), (4, 22), (6, 2), (8, 0), (99, 11)]
121 print( sorted(a.items(),key =lambda x:x[1]) ) #[(8, 0), (6, 2), (1, 4), (-5, 6), (99, 11), (4, 22)] 用value拍
122
123
124
125 a = [1,2,3,4,5,6]
126 b = ['a','b','c','d']
127
128 for i in zip(a,b):
129 print(i) #组合(1, 'a') (2, 'b') (3, 'c') (4, 'd')
130
131
132
133 import decorator
134 __import__('decorator') #只知道字符串导入方法