Python小例子:https://github.com/jackzhenguo/python-small-examples
贡献
欢迎贡献小例子到此库
License
允许按照要求转载,但禁止用于任何商用目的。
小例子
一、 数字
1 求绝对值
绝对值或复数的模
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">abs</span>(<span style="color: #005cc5;">-</span><span style="color: #005cc5;">6</span>)
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">1</span>]: <span style="color: #005cc5;">6</span>
2 进制转化
十进制转换为二进制:
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">2</span>]: <span style="color: #6f42c1;">bin</span>(<span style="color: #005cc5;">10</span>)
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">2</span>]: <span style="color: #032f62;">'0b1010'</span>
十进制转换为八进制:
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">3</span>]: <span style="color: #6f42c1;">oct</span>(<span style="color: #005cc5;">9</span>)
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">3</span>]: <span style="color: #032f62;">'0o11'</span>
十进制转换为十六进制:
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">4</span>]: <span style="color: #6f42c1;">hex</span>(<span style="color: #005cc5;">15</span>)
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">4</span>]: <span style="color: #032f62;">'0xf'</span>
3 整数和ASCII互转
十进制整数对应的ASCII字符
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">chr</span>(<span style="color: #005cc5;">65</span>)
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">1</span>]: <span style="color: #032f62;">'A'</span>
查看某个ASCII字符
对应的十进制数
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">ord</span>(<span style="color: #032f62;">'A'</span>)
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">1</span>]: <span style="color: #005cc5;">65</span>
4 元素都为真检查
所有元素都为真,返回 True
,否则为False
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">5</span>]: <span style="color: #6f42c1;">all</span>([<span style="color: #005cc5;">1</span>,<span style="color: #005cc5;">0</span>,<span style="color: #005cc5;">3</span>,<span style="color: #005cc5;">6</span>])
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">5</span>]: <span style="color: #005cc5;">False</span>
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">6</span>]: <span style="color: #6f42c1;">all</span>([<span style="color: #005cc5;">1</span>,<span style="color: #005cc5;">2</span>,<span style="color: #005cc5;">3</span>])
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">6</span>]: <span style="color: #005cc5;">True</span>
5 元素至少一个为真检查
至少有一个元素为真返回True
,否则False
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">7</span>]: <span style="color: #6f42c1;">any</span>([<span style="color: #005cc5;">0</span>,<span style="color: #005cc5;">0</span>,<span style="color: #005cc5;">0</span>,[]])
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">7</span>]: <span style="color: #005cc5;">False</span>
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">8</span>]: <span style="color: #6f42c1;">any</span>([<span style="color: #005cc5;">0</span>,<span style="color: #005cc5;">0</span>,<span style="color: #005cc5;">1</span>])
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">8</span>]: <span style="color: #005cc5;">True</span>
6 判断是真是假
测试一个对象是True, 还是False.
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">9</span>]: <span style="color: #6f42c1;">bool</span>([<span style="color: #005cc5;">0</span>,<span style="color: #005cc5;">0</span>,<span style="color: #005cc5;">0</span>])
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">9</span>]: <span style="color: #005cc5;">True</span>
In [10]: bool([])
Out[10]: False
In [11]: bool([1,0,1])
Out[11]: True
7 创建复数
创建一个复数
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">complex</span>(<span style="color: #005cc5;">1</span>,<span style="color: #005cc5;">2</span>)
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">1</span>]: (<span style="color: #005cc5;">1</span><span style="color: #005cc5;">+</span><span style="color: #005cc5;">2j</span>)
8 取商和余数
分别取商和余数
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">divmod</span>(<span style="color: #005cc5;">10</span>,<span style="color: #005cc5;">3</span>)
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">1</span>]: (<span style="color: #005cc5;">3</span>, <span style="color: #005cc5;">1</span>)
9 转为浮点类型
将一个整数或数值型字符串转换为浮点数
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">float</span>(<span style="color: #005cc5;">3</span>)
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">1</span>]: <span style="color: #005cc5;">3.0</span>
如果不能转化为浮点数,则会报ValueError
:
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">2</span>]: <span style="color: #6f42c1;">float</span>(<span style="color: #032f62;">'a'</span>)
<span style="color: #6a737d;"># ValueError: could not convert string to float: 'a'</span>
10 转为整型
int(x, base =10) , x可能为字符串或数值,将x 转换为一个普通整数。如果参数是字符串,那么它可能包含符号和小数点。如果超出了普通整数的表示范围,一个长整数被返回。
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">int</span>(<span style="color: #032f62;">'12'</span>,<span style="color: #005cc5;">16</span>)
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">1</span>]: <span style="color: #005cc5;">18</span>
11 次幂
base为底的exp次幂,如果mod给出,取余
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">pow</span>(<span style="color: #005cc5;">3</span>, <span style="color: #005cc5;">2</span>, <span style="color: #005cc5;">4</span>)
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">1</span>]: <span style="color: #005cc5;">1</span>
12 四舍五入
四舍五入,ndigits
代表小数点后保留几位:
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">11</span>]: <span style="color: #6f42c1;">round</span>(<span style="color: #005cc5;">10.0222222</span>, <span style="color: #005cc5;">3</span>)
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">11</span>]: <span style="color: #005cc5;">10.022</span>
In [12]: round(10.05,1)
Out[12]: 10.1
13 链式比较
i <span style="color: #005cc5;">=</span> <span style="color: #005cc5;">3</span>
<span style="color: #6f42c1;">print</span>(<span style="color: #005cc5;">1</span> <span style="color: #005cc5;"><</span> i <span style="color: #005cc5;"><</span> <span style="color: #005cc5;">3</span>) <span style="color: #6a737d;"># False</span>
<span style="color: #6f42c1;">print</span>(<span style="color: #005cc5;">1</span> <span style="color: #005cc5;"><</span> i <span style="color: #005cc5;"><=</span> <span style="color: #005cc5;">3</span>) <span style="color: #6a737d;"># True</span>
二、 字符串
14 字符串转字节
字符串转换为字节类型
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">12</span>]: s <span style="color: #005cc5;">=</span> <span style="color: #032f62;">"apple"</span>
In [13]: bytes(s,encoding='utf-8')
Out[13]: b'apple'
15 任意对象转为字符串
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">14</span>]: i <span style="color: #005cc5;">=</span> <span style="color: #005cc5;">100</span>
In [15]: str(i)
Out[15]: '100'
In [16]: str([])
Out[16]: '[]'
In [17]: str(tuple())
Out[17]: '()'
16 执行字符串表示的代码
将字符串编译成python能识别或可执行的代码,也可以将文字读成字符串再编译。
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: s <span style="color: #005cc5;">=</span> <span style="color: #032f62;">"print('helloworld')"</span>
In [2]: r = compile(s,"<string>", "exec")
In [3]: r
Out[3]: <code object <module> at 0x0000000005DE75D0, file "<string>", line 1>
In [4]: exec(r)
helloworld
17 计算表达式
将字符串str 当成有效的表达式来求值并返回计算结果取出字符串中内容
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: s <span style="color: #005cc5;">=</span> <span style="color: #032f62;">"1 + 3 +5"</span>
...: <span style="color: #6f42c1;">eval</span>(s)
...:
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">1</span>]: <span style="color: #005cc5;">9</span>
18 字符串格式化
格式化输出字符串,format(value, format_spec)实质上是调用了value的__format__(format_spec)方法。
In [104]: print("i am {0},age{1}".format("tom",18))
i am tom,age18
3.1415926 | {:.2f} | 3.14 | 保留小数点后两位 |
---|---|---|---|
3.1415926 | {:+.2f} | +3.14 | 带符号保留小数点后两位 |
-1 | {:+.2f} | -1.00 | 带符号保留小数点后两位 |
2.71828 | {:.0f} | 3 | 不带小数 |
5 | {:0>2d} | 05 | 数字补零 (填充左边, 宽度为2) |
5 | {:x<4d} | 5xxx | 数字补x (填充右边, 宽度为4) |
10 | {:x<4d} | 10xx | 数字补x (填充右边, 宽度为4) |
1000000 | {:,} | 1,000,000 | 以逗号分隔的数字格式 |
0.25 | {:.2%} | 25.00% | 百分比格式 |
1000000000 | {:.2e} | 1.00e+09 | 指数记法 |
18 | {:>10d} | ' 18' | 右对齐 (默认, 宽度为10) |
18 | {:<10d} | '18 ' | 左对齐 (宽度为10) |
18 | {:^10d} | ' 18 ' | 中间对齐 (宽度为10) |
三、 函数
19 拿来就用的排序函数
排序:
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: a <span style="color: #005cc5;">=</span> [<span style="color: #005cc5;">1</span>,<span style="color: #005cc5;">4</span>,<span style="color: #005cc5;">2</span>,<span style="color: #005cc5;">3</span>,<span style="color: #005cc5;">1</span>]
In [2]: sorted(a,reverse=True)
Out[2]: [4, 3, 2, 1, 1]
In [3]: a = [{'name':'xiaoming','age':18,'gender':'male'},{'name':'
...: xiaohong','age':20,'gender':'female'}]
In [4]: sorted(a,key=lambda x: x['age'],reverse=False)
Out[4]:
[{'name': 'xiaoming', 'age': 18, 'gender': 'male'},
{'name': 'xiaohong', 'age': 20, 'gender': 'female'}]
20 求和函数
求和:
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">181</span>]: a <span style="color: #005cc5;">=</span> [<span style="color: #005cc5;">1</span>,<span style="color: #005cc5;">4</span>,<span style="color: #005cc5;">2</span>,<span style="color: #005cc5;">3</span>,<span style="color: #005cc5;">1</span>]
In [182]: sum(a)
Out[182]: 11
In [185]: sum(a,10) #求和的初始值为10
Out[185]: 21
21 nonlocal用于内嵌函数中
关键词nonlocal
常用于函数嵌套中,声明变量i
为非局部变量;如果不声明,i+=1
表明i
为函数wrapper
内的局部变量,因为在i+=1
引用(reference)时,i未被声明,所以会报unreferenced variable
的错误。
<span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">excepter</span>(f):
i <span style="color: #005cc5;">=</span> <span style="color: #005cc5;">0</span>
t1 <span style="color: #005cc5;">=</span> time.<span style="color: #6f42c1;">time</span>()
<span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">wrapper</span>():
<span style="color: #d73a49;">try</span>:
<span style="color: #6f42c1;">f</span>()
<span style="color: #d73a49;">except</span> <span style="color: #e36209;">Exception</span> <span style="color: #d73a49;">as</span> e:
<span style="color: #d73a49;">nonlocal</span> i
i <span style="color: #005cc5;">+=</span> <span style="color: #005cc5;">1</span>
<span style="color: #6f42c1;">print</span>(<span style="color: #032f62;">f'<span style="color: #24292e;">{e.args[<span style="color: #005cc5;">0</span>]}</span>: <span style="color: #24292e;">{i}</span>'</span>)
t2 <span style="color: #005cc5;">=</span> time.<span style="color: #6f42c1;">time</span>()
<span style="color: #d73a49;">if</span> i <span style="color: #005cc5;">==</span> n:
<span style="color: #6f42c1;">print</span>(<span style="color: #032f62;">f'spending time:<span style="color: #24292e;">{<span style="color: #6f42c1;">round</span>(t2<span style="color: #005cc5;">-</span>t1,<span style="color: #005cc5;">2</span>)}</span>'</span>)
<span style="color: #d73a49;">return</span> wrapper
22 global 声明全局变量
先回答为什么要有global
,一个变量被多个函数引用,想让全局变量被所有函数共享。有的伙伴可能会想这还不简单,这样写:
i <span style="color: #005cc5;">=</span> <span style="color: #005cc5;">5</span>
<span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">f</span>():
<span style="color: #6f42c1;">print</span>(i)
def g():
print(i)
pass
f()
g()
f和g两个函数都能共享变量i
,程序没有报错,所以他们依然不明白为什么要用global
.
但是,如果我想要有个函数对i
递增,这样:
<span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">h</span>():
i <span style="color: #005cc5;">+=</span> <span style="color: #005cc5;">1</span>
h()
此时执行程序,bang, 出错了!抛出异常:UnboundLocalError
,原来编译器在解释i+=1
时会把i
解析为函数h()
内的局部变量,很显然在此函数内,编译器找不到对变量i
的定义,所以会报错。
global
就是为解决此问题而被提出,在函数h内,显式地告诉编译器i
为全局变量,然后编译器会在函数外面寻找i
的定义,执行完i+=1
后,i
还为全局变量,值加1:
i <span style="color: #005cc5;">=</span> <span style="color: #005cc5;">0</span>
<span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">h</span>():
<span style="color: #d73a49;">global</span> i
i <span style="color: #005cc5;">+=</span> <span style="color: #005cc5;">1</span>
h()
print(i)
23 交换两元素
<span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">swap</span>(a, b):
<span style="color: #d73a49;">return</span> b, a
print(swap(1, 0)) # (0,1)
24 操作函数对象
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">31</span>]: def <span style="color: #6f42c1;">f</span>():
...: <span style="color: #6f42c1;">print</span>(<span style="color: #032f62;">'i'm f'</span>)
...:
In [32]: def g():
...: print('i'm g')
...:
In [33]: [f,g][1]()
i'm g
创建函数对象的list,根据想要调用的index,方便统一调用。
25 生成逆序序列
<span style="color: #6f42c1;">list</span>(<span style="color: #6f42c1;">range</span>(<span style="color: #005cc5;">10</span>,<span style="color: #005cc5;">-</span><span style="color: #005cc5;">1</span>,<span style="color: #005cc5;">-</span><span style="color: #005cc5;">1</span>)) <span style="color: #6a737d;"># [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]</span>
第三个参数为负时,表示从第一个参数开始递减,终止到第二个参数(不包括此边界)
26 函数的五类参数使用例子
python五类参数:位置参数,关键字参数,默认参数,可变位置或关键字参数的使用。
<span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">f</span>(a,<span style="color: #005cc5;">*</span>b,c<span style="color: #005cc5;">=</span><span style="color: #005cc5;">10</span>,<span style="color: #005cc5;">**</span>d):
<span style="color: #6f42c1;">print</span>(<span style="color: #032f62;">f'a:<span style="color: #24292e;">{a}</span>,b:<span style="color: #24292e;">{b}</span>,c:<span style="color: #24292e;">{c}</span>,d:<span style="color: #24292e;">{d}</span>'</span>)
默认参数c
不能位于可变关键字参数d
后.
调用f:
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">10</span>]: <span style="color: #6f42c1;">f</span>(<span style="color: #005cc5;">1</span>,<span style="color: #005cc5;">2</span>,<span style="color: #005cc5;">5</span>,width<span style="color: #005cc5;">=</span><span style="color: #005cc5;">10</span>,height<span style="color: #005cc5;">=</span><span style="color: #005cc5;">20</span>)
a:<span style="color: #005cc5;">1</span>,b:(<span style="color: #005cc5;">2</span>, <span style="color: #005cc5;">5</span>),c:<span style="color: #005cc5;">10</span>,d:{<span style="color: #032f62;">'width'</span>: <span style="color: #005cc5;">10</span>, <span style="color: #032f62;">'height'</span>: <span style="color: #005cc5;">20</span>}
可变位置参数b
实参后被解析为元组(2,5)
;而c取得默认值10; d被解析为字典.
再次调用f:
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">11</span>]: <span style="color: #6f42c1;">f</span>(a<span style="color: #005cc5;">=</span><span style="color: #005cc5;">1</span>,c<span style="color: #005cc5;">=</span><span style="color: #005cc5;">12</span>)
a:<span style="color: #005cc5;">1</span>,b:(),c:<span style="color: #005cc5;">12</span>,d:{}
a=1传入时a就是关键字参数,b,d都未传值,c被传入12,而非默认值。
注意观察参数a
, 既可以f(1)
,也可以f(a=1)
其可读性比第一种更好,建议使用f(a=1)。如果要强制使用f(a=1)
,需要在前面添加一个星号:
<span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">f</span>(*,a,<span style="color: #005cc5;">**</span>b):
<span style="color: #6f42c1;">print</span>(<span style="color: #032f62;">f'a:<span style="color: #24292e;">{a}</span>,b:<span style="color: #24292e;">{b}</span>'</span>)
此时f(1)调用,将会报错:TypeError: f() takes 0 positional arguments but 1 was given
只能f(a=1)
才能OK.
说明前面的*
发挥作用,它变为只能传入关键字参数,那么如何查看这个参数的类型呢?借助python的inspect
模块:
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">22</span>]: for name,val <span style="color: #005cc5;">in</span> <span style="color: #6f42c1;">signature</span>(f).parameters.<span style="color: #6f42c1;">items</span>():
...: <span style="color: #6f42c1;">print</span>(name,val.kind)
...:
a <span style="color: #e36209;">KEYWORD_ONLY</span>
b <span style="color: #e36209;">VAR_KEYWORD</span>
可看到参数a
的类型为KEYWORD_ONLY
,也就是仅仅为关键字参数。
但是,如果f定义为:
<span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">f</span>(a,<span style="color: #005cc5;">*</span>b):
<span style="color: #6f42c1;">print</span>(<span style="color: #032f62;">f'a:<span style="color: #24292e;">{a}</span>,b:<span style="color: #24292e;">{b}</span>'</span>)
查看参数类型:
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">24</span>]: for name,val <span style="color: #005cc5;">in</span> <span style="color: #6f42c1;">signature</span>(f).parameters.<span style="color: #6f42c1;">items</span>():
...: <span style="color: #6f42c1;">print</span>(name,val.kind)
...:
a <span style="color: #e36209;">POSITIONAL_OR_KEYWORD</span>
b <span style="color: #e36209;">VAR_POSITIONAL</span>
可以看到参数a
既可以是位置参数也可是关键字参数。
27 使用slice对象
生成关于蛋糕的序列cake1:
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: cake1 <span style="color: #005cc5;">=</span> <span style="color: #6f42c1;">list</span>(<span style="color: #6f42c1;">range</span>(<span style="color: #005cc5;">5</span>,<span style="color: #005cc5;">0</span>,<span style="color: #005cc5;">-</span><span style="color: #005cc5;">1</span>))
In [2]: b = cake1[1:10:2]
In [3]: b
Out[3]: [4, 2]
In [4]: cake1
Out[4]: [5, 4, 3, 2, 1]
再生成一个序列:
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">5</span>]: from random <span style="color: #d73a49;">import</span> randint
...: cake2 <span style="color: #005cc5;">=</span> [<span style="color: #6f42c1;">randint</span>(<span style="color: #005cc5;">1</span>,<span style="color: #005cc5;">100</span>) <span style="color: #d73a49;">for</span> _ <span style="color: #005cc5;">in</span> <span style="color: #6f42c1;">range</span>(<span style="color: #005cc5;">100</span>)]
...: <span style="color: #6a737d;"># 同样以间隔为2切前10个元素,得到切片d</span>
...: d <span style="color: #005cc5;">=</span> cake2[<span style="color: #005cc5;">1</span>:<span style="color: #005cc5;">10</span>:<span style="color: #005cc5;">2</span>]
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">6</span>]: d
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">6</span>]: [<span style="color: #005cc5;">75</span>, <span style="color: #005cc5;">33</span>, <span style="color: #005cc5;">63</span>, <span style="color: #005cc5;">93</span>, <span style="color: #005cc5;">15</span>]
你看,我们使用同一种切法,分别切开两个蛋糕cake1,cake2. 后来发现这种切法极为经典
,又拿它去切更多的容器对象。
那么,为什么不把这种切法封装为一个对象呢?于是就有了slice对象。
定义slice对象极为简单,如把上面的切法定义成slice对象:
perfect_cake_slice_way <span style="color: #005cc5;">=</span> <span style="color: #6f42c1;">slice</span>(<span style="color: #005cc5;">1</span>,<span style="color: #005cc5;">10</span>,<span style="color: #005cc5;">2</span>)
<span style="color: #6a737d;">#去切cake1</span>
cake1_slice <span style="color: #005cc5;">=</span> cake1[perfect_cake_slice_way]
cake2_slice <span style="color: #005cc5;">=</span> cake2[perfect_cake_slice_way]
In [11]: cake1_slice
Out[11]: [4, 2]
In [12]: cake2_slice
Out[12]: [75, 33, 63, 93, 15]
与上面的结果一致。
对于逆向序列切片,slice
对象一样可行:
a <span style="color: #005cc5;">=</span> [<span style="color: #005cc5;">1</span>,<span style="color: #005cc5;">3</span>,<span style="color: #005cc5;">5</span>,<span style="color: #005cc5;">7</span>,<span style="color: #005cc5;">9</span>,<span style="color: #005cc5;">0</span>,<span style="color: #005cc5;">3</span>,<span style="color: #005cc5;">5</span>,<span style="color: #005cc5;">7</span>]
a_ <span style="color: #005cc5;">=</span> a[<span style="color: #005cc5;">5</span>:<span style="color: #005cc5;">1</span>:<span style="color: #005cc5;">-</span><span style="color: #005cc5;">1</span>]
named_slice = slice(5,1,-1)
a_slice = a[named_slice]
In [14]: a_
Out[14]: [0, 9, 7, 5]
In [15]: a_slice
Out[15]: [0, 9, 7, 5]
频繁使用同一切片的操作可使用slice对象抽出来,复用的同时还能提高代码可读性。
28 lambda 函数的动画演示
有些读者反映,lambda
函数不太会用,问我能不能解释一下。
比如,下面求这个 lambda
函数:
<span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">max_len</span>(<span style="color: #005cc5;">*</span>lists):
<span style="color: #d73a49;">return</span> <span style="color: #6f42c1;">max</span>(<span style="color: #005cc5;">*</span>lists, key<span style="color: #005cc5;">=</span><span style="color: #d73a49;">lambda</span> v: <span style="color: #6f42c1;">len</span>(v))
有两点疑惑:
- 参数
v
的取值? lambda
函数有返回值吗?如果有,返回值是多少?
调用上面函数,求出以下三个最长的列表:
r <span style="color: #005cc5;">=</span> <span style="color: #6f42c1;">max_len</span>([<span style="color: #005cc5;">1</span>, <span style="color: #005cc5;">2</span>, <span style="color: #005cc5;">3</span>], [<span style="color: #005cc5;">4</span>, <span style="color: #005cc5;">5</span>, <span style="color: #005cc5;">6</span>, <span style="color: #005cc5;">7</span>], [<span style="color: #005cc5;">8</span>])
<span style="color: #6f42c1;">print</span>(<span style="color: #032f62;">f'更长的列表是<span style="color: #24292e;">{r}</span>'</span>)
程序完整运行过程,动画演示如下:
结论:
-
参数v的可能取值为
*lists
,也就是tuple
的一个元素。 -
lambda
函数返回值,等于lambda v
冒号后表达式的返回值。
四、 数据结构
29 转为字典
创建数据字典
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">dict</span>()
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">1</span>]: {}
In [2]: dict(a='a',b='b')
Out[2]: {'a': 'a', 'b': 'b'}
In [3]: dict(zip(['a','b'],[1,2]))
Out[3]: {'a': 1, 'b': 2}
In [4]: dict([('a',1),('b',2)])
Out[4]: {'a': 1, 'b': 2}
30 冻结集合
创建一个不可修改的集合。
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">frozenset</span>([<span style="color: #005cc5;">1</span>,<span style="color: #005cc5;">1</span>,<span style="color: #005cc5;">3</span>,<span style="color: #005cc5;">2</span>,<span style="color: #005cc5;">3</span>])
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">frozenset</span>({<span style="color: #005cc5;">1</span>, <span style="color: #005cc5;">2</span>, <span style="color: #005cc5;">3</span>})
因为不可修改,所以没有像set
那样的add
和pop
方法
31 转为集合类型
返回一个set对象,集合内不允许有重复元素:
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">159</span>]: a <span style="color: #005cc5;">=</span> [<span style="color: #005cc5;">1</span>,<span style="color: #005cc5;">4</span>,<span style="color: #005cc5;">2</span>,<span style="color: #005cc5;">3</span>,<span style="color: #005cc5;">1</span>]
In [160]: set(a)
Out[160]: {1, 2, 3, 4}
32 转为切片对象
class slice(start, stop[, step])
返回一个表示由 range(start, stop, step) 所指定索引集的 slice对象,它让代码可读性、可维护性变好。
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: a <span style="color: #005cc5;">=</span> [<span style="color: #005cc5;">1</span>,<span style="color: #005cc5;">4</span>,<span style="color: #005cc5;">2</span>,<span style="color: #005cc5;">3</span>,<span style="color: #005cc5;">1</span>]
In [2]: my_slice_meaning = slice(0,5,2)
In [3]: a[my_slice_meaning]
Out[3]: [1, 2, 1]
33 转元组
tuple()
将对象转为一个不可变的序列类型
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">16</span>]: i_am_list <span style="color: #005cc5;">=</span> [<span style="color: #005cc5;">1</span>,<span style="color: #005cc5;">3</span>,<span style="color: #005cc5;">5</span>]
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">17</span>]: i_am_tuple <span style="color: #005cc5;">=</span> <span style="color: #6f42c1;">tuple</span>(i_am_list)
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">18</span>]: i_am_tuple
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">18</span>]: (<span style="color: #005cc5;">1</span>, <span style="color: #005cc5;">3</span>, <span style="color: #005cc5;">5</span>)
五、 类和对象
34 是否可调用
检查对象是否可被调用
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">callable</span>(str)
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">1</span>]: <span style="color: #005cc5;">True</span>
In [2]: callable(int)
Out[2]: True
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">18</span>]: class <span style="color: #e36209;">Student</span>():
...: <span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">__init__</span>(self,id,name):
...: self.id <span style="color: #005cc5;">=</span> id
...: self.name <span style="color: #005cc5;">=</span> name
...: def <span style="color: #6f42c1;">__repr__</span>(self):
...: <span style="color: #d73a49;">return</span> <span style="color: #032f62;">'id = '</span><span style="color: #005cc5;">+</span>self.id <span style="color: #005cc5;">+</span><span style="color: #032f62;">', name = '</span><span style="color: #005cc5;">+</span>self.name
...
In [19]: xiaoming = Student('001','xiaoming')
In [20]: callable(xiaoming)
Out[20]: False
如果能调用xiaoming()
, 需要重写Student
类的__call__
方法:
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: class <span style="color: #e36209;">Student</span>():
...: <span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">__init__</span>(self,id,name):
...: self.id <span style="color: #005cc5;">=</span> id
...: self.name <span style="color: #005cc5;">=</span> name
...: def <span style="color: #6f42c1;">__repr__</span>(self):
...: <span style="color: #d73a49;">return</span> <span style="color: #032f62;">'id = '</span><span style="color: #005cc5;">+</span>self.id <span style="color: #005cc5;">+</span><span style="color: #032f62;">', name = '</span><span style="color: #005cc5;">+</span>self.name
...: def <span style="color: #6f42c1;">__call__</span>(self):
...: <span style="color: #6f42c1;">print</span>(<span style="color: #032f62;">'I can be called'</span>)
...: <span style="color: #6f42c1;">print</span>(<span style="color: #032f62;">f'my name is <span style="color: #24292e;">{self.name}</span>'</span>)
...:
In [2]: t = Student('001','xiaoming')
In [3]: t()
I can be called
my name is xiaoming
35 ascii 展示对象
调用对象的 __repr__
方法,获得该方法的返回值,如下例子返回值为字符串
<span style="color: #005cc5;">>></span><span style="color: #005cc5;">></span> <span style="color: #d73a49;">class</span> <span style="color: #e36209;">Student</span>():
<span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">__init__</span>(self,id,name):
self.id <span style="color: #005cc5;">=</span> id
self.name <span style="color: #005cc5;">=</span> name
<span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">__repr__</span>(self):
<span style="color: #d73a49;">return</span> <span style="color: #032f62;">'id = '</span><span style="color: #005cc5;">+</span>self.id <span style="color: #005cc5;">+</span><span style="color: #032f62;">', name = '</span><span style="color: #005cc5;">+</span>self.name
调用:
<span style="color: #005cc5;">>></span><span style="color: #005cc5;">></span> xiaoming <span style="color: #005cc5;">=</span> <span style="color: #e36209;">Student</span>(id<span style="color: #005cc5;">=</span><span style="color: #032f62;">'1'</span>,name<span style="color: #005cc5;">=</span><span style="color: #032f62;">'xiaoming'</span>)
<span style="color: #005cc5;">>></span><span style="color: #005cc5;">></span> xiaoming
id <span style="color: #005cc5;">=</span> <span style="color: #005cc5;">1</span>, name <span style="color: #005cc5;">=</span> xiaoming
<span style="color: #005cc5;">>></span><span style="color: #005cc5;">></span> <span style="color: #6f42c1;">ascii</span>(xiaoming)
<span style="color: #032f62;">'id = 1, name = xiaoming'</span>
36 类方法
classmethod
装饰器对应的函数不需要实例化,不需要 self
参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: class <span style="color: #e36209;">Student</span>():
...: <span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">__init__</span>(self,id,name):
...: self.id <span style="color: #005cc5;">=</span> id
...: self.name <span style="color: #005cc5;">=</span> name
...: def <span style="color: #6f42c1;">__repr__</span>(self):
...: <span style="color: #d73a49;">return</span> <span style="color: #032f62;">'id = '</span><span style="color: #005cc5;">+</span>self.id <span style="color: #005cc5;">+</span><span style="color: #032f62;">', name = '</span><span style="color: #005cc5;">+</span>self.name
...: @classmethod
...: def <span style="color: #6f42c1;">f</span>(cls):
...: <span style="color: #6f42c1;">print</span>(cls)
37 动态删除属性
删除对象的属性
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">delattr</span>(xiaoming,<span style="color: #032f62;">'id'</span>)
In [2]: hasattr(xiaoming,'id')
Out[2]: False
38 一键查看对象所有方法
不带参数时返回当前范围
内的变量、方法和定义的类型列表;带参数时返回参数
的属性,方法列表。
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">96</span>]: <span style="color: #6f42c1;">dir</span>(xiaoming)
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">96</span>]:
[<span style="color: #032f62;">'__class__'</span>,
<span style="color: #032f62;">'__delattr__'</span>,
<span style="color: #032f62;">'__dict__'</span>,
<span style="color: #032f62;">'__dir__'</span>,
<span style="color: #032f62;">'__doc__'</span>,
<span style="color: #032f62;">'__eq__'</span>,
<span style="color: #032f62;">'__format__'</span>,
<span style="color: #032f62;">'__ge__'</span>,
<span style="color: #032f62;">'__getattribute__'</span>,
<span style="color: #032f62;">'__gt__'</span>,
<span style="color: #032f62;">'__hash__'</span>,
<span style="color: #032f62;">'__init__'</span>,
<span style="color: #032f62;">'__init_subclass__'</span>,
<span style="color: #032f62;">'__le__'</span>,
<span style="color: #032f62;">'__lt__'</span>,
<span style="color: #032f62;">'__module__'</span>,
<span style="color: #032f62;">'__ne__'</span>,
<span style="color: #032f62;">'__new__'</span>,
<span style="color: #032f62;">'__reduce__'</span>,
<span style="color: #032f62;">'__reduce_ex__'</span>,
<span style="color: #032f62;">'__repr__'</span>,
<span style="color: #032f62;">'__setattr__'</span>,
<span style="color: #032f62;">'__sizeof__'</span>,
<span style="color: #032f62;">'__str__'</span>,
<span style="color: #032f62;">'__subclasshook__'</span>,
<span style="color: #032f62;">'__weakref__'</span>,
'name']
39 动态获取对象属性
获取对象的属性
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: class <span style="color: #e36209;">Student</span>():
...: <span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">__init__</span>(self,id,name):
...: self.id <span style="color: #005cc5;">=</span> id
...: self.name <span style="color: #005cc5;">=</span> name
...: def <span style="color: #6f42c1;">__repr__</span>(self):
...: <span style="color: #d73a49;">return</span> <span style="color: #032f62;">'id = '</span><span style="color: #005cc5;">+</span>self.id <span style="color: #005cc5;">+</span><span style="color: #032f62;">', name = '</span><span style="color: #005cc5;">+</span>self.name
In [2]: xiaoming = Student(id='001',name='xiaoming')
In [3]: getattr(xiaoming,'name') # 获取xiaoming这个实例的name属性值
Out[3]: 'xiaoming'
40 对象是否有这个属性
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: class <span style="color: #e36209;">Student</span>():
...: <span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">__init__</span>(self,id,name):
...: self.id <span style="color: #005cc5;">=</span> id
...: self.name <span style="color: #005cc5;">=</span> name
...: def <span style="color: #6f42c1;">__repr__</span>(self):
...: <span style="color: #d73a49;">return</span> <span style="color: #032f62;">'id = '</span><span style="color: #005cc5;">+</span>self.id <span style="color: #005cc5;">+</span><span style="color: #032f62;">', name = '</span><span style="color: #005cc5;">+</span>self.name
In [2]: xiaoming = Student(id='001',name='xiaoming')
In [3]: hasattr(xiaoming,'name')
Out[3]: True
In [4]: hasattr(xiaoming,'address')
Out[4]: False
41 对象门牌号
返回对象的内存地址
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">id</span>(xiaoming)
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">1</span>]: <span style="color: #005cc5;">98234208</span>
42 isinstance
判断object是否为类classinfo的实例,是返回true
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: class <span style="color: #e36209;">Student</span>():
...: <span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">__init__</span>(self,id,name):
...: self.id <span style="color: #005cc5;">=</span> id
...: self.name <span style="color: #005cc5;">=</span> name
...: def <span style="color: #6f42c1;">__repr__</span>(self):
...: <span style="color: #d73a49;">return</span> <span style="color: #032f62;">'id = '</span><span style="color: #005cc5;">+</span>self.id <span style="color: #005cc5;">+</span><span style="color: #032f62;">', name = '</span><span style="color: #005cc5;">+</span>self.name
In [2]: xiaoming = Student(id='001',name='xiaoming')
In [3]: isinstance(xiaoming,Student)
Out[3]: True
43 父子关系鉴定
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: class <span style="color: #6f42c1;">undergraduate</span>(<span style="color: #e36209;">Student</span>):
...: <span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">studyClass</span>(self):
...: pass
...: def <span style="color: #6f42c1;">attendActivity</span>(self):
...: pass
In [2]: issubclass(undergraduate,Student)
Out[2]: True
In [3]: issubclass(object,Student)
Out[3]: False
In [4]: issubclass(Student,object)
Out[4]: True
如果class是classinfo元组中某个元素的子类,也会返回True
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">issubclass</span>(int,(int,float))
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">1</span>]: <span style="color: #005cc5;">True</span>
44 所有对象之根
object 是所有类的基类
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: o <span style="color: #005cc5;">=</span> <span style="color: #6f42c1;">object</span>()
In [2]: type(o)
Out[2]: object
45 创建属性的两种方式
返回 property 属性,典型的用法:
<span style="color: #d73a49;">class</span> <span style="color: #e36209;">C</span>:
<span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">__init__</span>(self):
self._x <span style="color: #005cc5;">=</span> <span style="color: #005cc5;">None</span>
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
# 使用property类创建 property 属性
x = property(getx, setx, delx, "I'm the 'x' property.")
使用python装饰器,实现与上完全一样的效果代码:
<span style="color: #d73a49;">class</span> <span style="color: #e36209;">C</span>:
<span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">__init__</span>(self):
self._x <span style="color: #005cc5;">=</span> <span style="color: #005cc5;">None</span>
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
46 查看对象类型
class type
(name, bases, dict)
传入一个参数时,返回 object 的类型:
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: class <span style="color: #e36209;">Student</span>():
...: <span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">__init__</span>(self,id,name):
...: self.id <span style="color: #005cc5;">=</span> id
...: self.name <span style="color: #005cc5;">=</span> name
...: def <span style="color: #6f42c1;">__repr__</span>(self):
...: <span style="color: #d73a49;">return</span> <span style="color: #032f62;">'id = '</span><span style="color: #005cc5;">+</span>self.id <span style="color: #005cc5;">+</span><span style="color: #032f62;">', name = '</span><span style="color: #005cc5;">+</span>self.name
...:
In [2]: xiaoming = Student(id='001',name='xiaoming')
In [3]: type(xiaoming)
Out[3]: __main__.Student
In [4]: type(tuple())
Out[4]: tuple
47 元类
xiaoming
, xiaohong
, xiaozhang
都是学生,这类群体叫做 Student
.
Python 定义类的常见方法,使用关键字 class
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">36</span>]: class <span style="color: #e36209;">Student</span>(object):
...: pass
xiaoming
, xiaohong
, xiaozhang
是类的实例,则:
xiaoming <span style="color: #005cc5;">=</span> <span style="color: #e36209;">Student</span>()
xiaohong <span style="color: #005cc5;">=</span> <span style="color: #e36209;">Student</span>()
xiaozhang <span style="color: #005cc5;">=</span> <span style="color: #e36209;">Student</span>()
创建后,xiaoming 的 __class__
属性,返回的便是 Student
类
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">38</span>]: xiaoming.__class__
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">38</span>]: __main__.<span style="color: #e36209;">Student</span>
问题在于,Student
类有 __class__
属性,如果有,返回的又是什么?
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">39</span>]: xiaoming.__class__.__class__
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">39</span>]: type
哇,程序没报错,返回 type
那么,我们不妨猜测:Student
类,类型就是 type
换句话说,Student
类就是一个对象,它的类型就是 type
所以,Python 中一切皆对象,类也是对象
Python 中,将描述 Student
类的类被称为:元类。
按照此逻辑延伸,描述元类的类被称为:元元类,开玩笑了~ 描述元类的类也被称为元类。
聪明的朋友会问了,既然 Student
类可创建实例,那么 type
类可创建实例吗?如果能,它创建的实例就叫:类 了。你们真聪明!
说对了,type
类一定能创建实例,比如 Student
类了。
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">40</span>]: <span style="color: #e36209;">Student</span> <span style="color: #005cc5;">=</span> <span style="color: #6f42c1;">type</span>(<span style="color: #032f62;">'Student'</span>,(),{})
In [41]: Student
Out[41]: __main__.Student
它与使用 class
关键字创建的 Student
类一模一样。
Python 的类,因为又是对象,所以和 xiaoming
,xiaohong
对象操作相似。支持:
- 赋值
- 拷贝
- 添加属性
- 作为函数参数
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">43</span>]: <span style="color: #e36209;">StudentMirror</span> <span style="color: #005cc5;">=</span> <span style="color: #e36209;">Student</span> <span style="color: #6a737d;"># 类直接赋值 # 类直接赋值</span>
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">44</span>]: <span style="color: #e36209;">Student</span>.class_property <span style="color: #005cc5;">=</span> <span style="color: #032f62;">'class_property'</span> <span style="color: #6a737d;"># 添加类属性</span>
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">46</span>]: <span style="color: #6f42c1;">hasattr</span>(<span style="color: #e36209;">Student</span>, <span style="color: #032f62;">'class_property'</span>)
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">46</span>]: <span style="color: #005cc5;">True</span>
元类,确实使用不是那么多,也许先了解这些,就能应付一些场合。就连 Python 界的领袖 Tim Peters
都说:
“元类就是深度的魔法,99%的用户应该根本不必为此操心。
六、工具
48 枚举对象
返回一个可以枚举的对象,该对象的next()方法将返回一个元组。
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: s <span style="color: #005cc5;">=</span> [<span style="color: #032f62;">"a"</span>,<span style="color: #032f62;">"b"</span>,<span style="color: #032f62;">"c"</span>]
...: for i ,v <span style="color: #005cc5;">in</span> <span style="color: #6f42c1;">enumerate</span>(s,<span style="color: #005cc5;">1</span>):
...: <span style="color: #6f42c1;">print</span>(i,v)
...:
<span style="color: #005cc5;">1</span> a
<span style="color: #005cc5;">2</span> b
<span style="color: #005cc5;">3</span> c
49 查看变量所占字节数
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: import sys
In [2]: a = {'a':1,'b':2.0}
In [3]: sys.getsizeof(a) # 占用240个字节
Out[3]: 240
50 过滤器
在函数中设定过滤条件,迭代元素,保留返回值为True
的元素:
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: fil <span style="color: #005cc5;">=</span> <span style="color: #6f42c1;">filter</span>(<span style="color: #d73a49;">lambda</span> x: x<span style="color: #005cc5;">></span><span style="color: #005cc5;">10</span>,[<span style="color: #005cc5;">1</span>,<span style="color: #005cc5;">11</span>,<span style="color: #005cc5;">2</span>,<span style="color: #005cc5;">45</span>,<span style="color: #005cc5;">7</span>,<span style="color: #005cc5;">6</span>,<span style="color: #005cc5;">13</span>])
In [2]: list(fil)
Out[2]: [11, 45, 13]
51 返回对象的哈希值
返回对象的哈希值,值得注意的是自定义的实例都是可哈希的,list
, dict
, set
等可变对象都是不可哈希的(unhashable)
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">hash</span>(xiaoming)
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">1</span>]: <span style="color: #005cc5;">6139638</span>
In [2]: hash([1,2,3])
# TypeError: unhashable type: 'list'
52 一键帮助
返回对象的帮助文档
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">help</span>(xiaoming)
<span style="color: #e36209;">Help</span> on <span style="color: #e36209;">Student</span> <span style="color: #005cc5;">in</span> module __main__ object:
class Student(builtins.object)
| Methods defined here:
|
| __init__(self, id, name)
|
| __repr__(self)
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
53 获取用户输入
获取用户输入内容
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">input</span>()
aa
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">1</span>]: <span style="color: #032f62;">'aa'</span>
54 创建迭代器类型
使用iter(obj, sentinel)
, 返回一个可迭代对象, sentinel可省略(一旦迭代到此元素,立即终止)
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: lst <span style="color: #005cc5;">=</span> [<span style="color: #005cc5;">1</span>,<span style="color: #005cc5;">3</span>,<span style="color: #005cc5;">5</span>]
In [2]: for i in iter(lst):
...: print(i)
...:
1
3
5
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: class <span style="color: #e36209;">TestIter</span>(object):
...: <span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">__init__</span>(self):
...: self.l<span style="color: #005cc5;">=</span>[<span style="color: #005cc5;">1</span>,<span style="color: #005cc5;">3</span>,<span style="color: #005cc5;">2</span>,<span style="color: #005cc5;">3</span>,<span style="color: #005cc5;">4</span>,<span style="color: #005cc5;">5</span>]
...: self.i<span style="color: #005cc5;">=</span><span style="color: #6f42c1;">iter</span>(self.l)
...: def <span style="color: #6f42c1;">__call__</span>(self): <span style="color: #6a737d;">#定义了__call__方法的类的实例是可调用的</span>
...: item <span style="color: #005cc5;">=</span> <span style="color: #6f42c1;">next</span>(self.i)
...: <span style="color: #6f42c1;">print</span> (<span style="color: #032f62;">"__call__ is called,fowhich would return"</span>,item)
...: return item
...: def <span style="color: #6f42c1;">__iter__</span>(self): <span style="color: #6a737d;">#支持迭代协议(即定义有__iter__()函数)</span>
...: <span style="color: #6f42c1;">print</span> (<span style="color: #032f62;">"__iter__ is called!!"</span>)
...: <span style="color: #6f42c1;">return</span> iter(self.l)
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">2</span>]: t <span style="color: #005cc5;">=</span> <span style="color: #e36209;">TestIter</span>()
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">3</span>]: <span style="color: #6f42c1;">t</span>() <span style="color: #6a737d;"># 因为实现了__call__,所以t实例能被调用</span>
__call__ <span style="color: #005cc5;">is</span> called,which would <span style="color: #d73a49;">return</span> <span style="color: #005cc5;">1</span>
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">3</span>]: <span style="color: #005cc5;">1</span>
In [4]: for e in TestIter(): # 因为实现了__iter__方法,所以t能被迭代
...: print(e)
...:
__iter__ is called!!
1
3
2
3
4
5
55 打开文件
返回文件对象
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: fo <span style="color: #005cc5;">=</span> <span style="color: #6f42c1;">open</span>(<span style="color: #032f62;">'D:/a.txt'</span>,mode<span style="color: #005cc5;">=</span><span style="color: #032f62;">'r'</span>, encoding<span style="color: #005cc5;">=</span><span style="color: #032f62;">'utf-8'</span>)
In [2]: fo.read()
Out[2]: 'ufefflife is not so long,nI use Python to play.'
mode取值表:
字符 | 意义 |
---|---|
'r' |
读取(默认) |
'w' |
写入,并先截断文件 |
'x' |
排它性创建,如果文件已存在则失败 |
'a' |
写入,如果文件存在则在末尾追加 |
'b' |
二进制模式 |
't' |
文本模式(默认) |
'+' |
打开用于更新(读取与写入) |
56 创建range序列
- range(stop)
- range(start, stop[,step])
生成一个不可变序列:
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">range</span>(<span style="color: #005cc5;">11</span>)
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">1</span>]: <span style="color: #6f42c1;">range</span>(<span style="color: #005cc5;">0</span>, <span style="color: #005cc5;">11</span>)
In [2]: range(0,11,1)
Out[2]: range(0, 11)
57 反向迭代器
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: rev <span style="color: #005cc5;">=</span> <span style="color: #6f42c1;">reversed</span>([<span style="color: #005cc5;">1</span>,<span style="color: #005cc5;">4</span>,<span style="color: #005cc5;">2</span>,<span style="color: #005cc5;">3</span>,<span style="color: #005cc5;">1</span>])
In [2]: for i in rev:
...: print(i)
...:
1
3
2
4
1
58 聚合迭代器
创建一个聚合了来自每个可迭代对象中的元素的迭代器:
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">1</span>]: x <span style="color: #005cc5;">=</span> [<span style="color: #005cc5;">3</span>,<span style="color: #005cc5;">2</span>,<span style="color: #005cc5;">1</span>]
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">2</span>]: y <span style="color: #005cc5;">=</span> [<span style="color: #005cc5;">4</span>,<span style="color: #005cc5;">5</span>,<span style="color: #005cc5;">6</span>]
<span style="color: #e36209;">In</span> [<span style="color: #005cc5;">3</span>]: <span style="color: #6f42c1;">list</span>(<span style="color: #6f42c1;">zip</span>(y,x))
<span style="color: #e36209;">Out</span>[<span style="color: #005cc5;">3</span>]: [(<span style="color: #005cc5;">4</span>, <span style="color: #005cc5;">3</span>), (<span style="color: #005cc5;">5</span>, <span style="color: #005cc5;">2</span>), (<span style="color: #005cc5;">6</span>, <span style="color: #005cc5;">1</span>)]
In [4]: a = range(5)
In [5]: b = list('abcde')
In [6]: b
Out[6]: ['a', 'b', 'c', 'd', 'e']
In [7]: [str(y) + str(x) for x,y in zip(a,b)]
Out[7]: ['a0', 'b1', 'c2', 'd3', 'e4']
59 链式操作
<span style="color: #d73a49;">from</span> operator <span style="color: #d73a49;">import</span> (add, sub)
def add_or_sub(a, b, oper):
return (add if oper == '+' else sub)(a, b)
add_or_sub(1, 2, '-') # -1
60 对象序列化
对象序列化,是指将内存中的对象转化为可存储或传输的过程。很多场景,直接一个类对象,传输不方便。
但是,当对象序列化后,就会更加方便,因为约定俗成的,接口间的调用或者发起的 web 请求,一般使用 json 串传输。
实际使用中,一般对类对象序列化。先创建一个 Student 类型,并创建两个实例。
<span style="color: #d73a49;">class</span> <span style="color: #e36209;">Student</span>():
<span style="color: #d73a49;">def</span> <span style="color: #6f42c1;">__init__</span>(self,<span style="color: #005cc5;">**</span>args):
self.ids <span style="color: #005cc5;">=</span> args[<span style="color: #032f62;">'ids'</span>]
self.name <span style="color: #005cc5;">=</span> args[<span style="color: #032f62;">'name'</span>]
self.address <span style="color: #005cc5;">=</span> args[<span style="color: #032f62;">'address'</span>]
xiaoming <span style="color: #005cc5;">=</span> <span style="color: #e36209;">Student</span>(ids <span style="color: #005cc5;">=</span> <span style="color: #005cc5;">1</span>,name <span style="color: #005cc5;">=</span> <span style="color: #032f62;">'xiaoming'</span>,address <span style="color: #005cc5;">=</span> <span style="color: #032f62;">'北京'</span>)
xiaohong <span style="color: #005cc5;">=</span> <span style="color: #e36209;">Student</span>(ids <span style="color: #005cc5;">=</span> <span style="color: #005cc5;">2</span>,name <span style="color: #005cc5;">=</span> <span style="color: #032f62;">'xiaohong'</span>,address <span style="color: #005cc5;">=</span> <span style="color: #032f62;">'南京'</span>)
导入 json 模块,调用 dump 方法,就会将列表对象 [xiaoming,xiaohong],序列化到文件 json.txt 中。
<span style="color: #d73a49;">import</span> json
with open('json.txt', 'w') as f:
json.dump([xiaoming,xiaohong], f, default=lambda obj: obj.__dict__, ensure_ascii=False, indent=2, sort_keys=True)
生成的文件内容,如下:
[
{
<span style="color: #032f62;">"address"</span>:<span style="color: #032f62;">"北京"</span>,
<span style="color: #032f62;">"ids"</span>:<span style="color: #005cc5;">1</span>,
<span style="color: #032f62;">"name"</span>:<span style="color: #032f62;">"xiaoming"</span>
},
{
<span style="color: #032f62;">"address"</span>:<span style="color: #032f62;">"南京"</span>,
<span style="color: #032f62;">"ids"</span>:<span style="color: #005cc5;">2</span>,
<span style="color: #032f62;">"name"</span>:<span style="color: #032f62;">"xiaohong"</span>
}
]
本文为原创文章,版权归知行编程网所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ 你用什么软件写Python代码?01/01
- ♥ 探究python int返回的方法01/09
- ♥ python词云安装什么库10/25
- ♥ python如何判断返回值类型10/02
- ♥ 什么是 python 格式化12/09
- ♥ 如何在python中输入连续字符08/21
内容反馈