16、用枚举在循环中找到索引
1 2 3 | test = [ 10 , 20 , 30 ] for i, value in enumerate (test): print (i, ':' , value) |
0 : 10
1 : 20
2 : 30
17、定义枚举量
1 2 3 4 5 6 | class shapes: circle, square, triangle, quadrangle = range ( 4 ) print (shapes.circle) print (shapes.square) print (shapes.triangle) print (shapes.quadrangle) |
0
1
2
3
18、从方法中返回多个值
1 2 3 4 | def x(): return 1 , 2 , 3 , 4 a, b, c, d = x() print (a, b, c, d) |
1 2 3 4
19、使用*运算符unpack函数参数
1 2 3 4 5 6 7 | def test(x, y, z): print (x, y, z) testDic = { 'x' : 1 , 'y' : 2 , 'z' : 3 } testList = [ 10 , 20 , 30 ] test( * testDic) test( * * testDic) test( * testList) |
z x y
1 2 3
10 20 30
20、用字典来存储表达式
1 2 3 4 5 6 | stdcalc = { "sum" : lambda x, y: x + y, "subtract" : lambda x, y: x - y } print (stdcalc[ "sum" ]( 9 , 3 )) print (stdcalc[ "subtract" ]( 9 , 3 )) |
12
6
21、计算任何数的阶乘
1 2 3 | import functools result = ( lambda k: functools. reduce ( int .__mul__, range ( 1 , k + 1 ), 1 ))( 3 ) print (result) |
6
22、找到列表中出现次数最多的数
1 2 | test = [ 1 , 2 , 3 , 4 , 2 , 2 , 3 , 1 , 4 , 4 , 4 , 4 ] print ( max ( set (test), key = test.count)) |
4
23、重置递归限制
python限制递归次数到1000,可以用下面方法重置
1 2 3 4 5 | import sys x = 1200 print (sys.getrecursionlimit()) sys.setrecursionlimit(x) print (sys.getrecursionlimit()) |
1000
1200
24、检查一个对象的内存使用
1 2 3 | import sys x = 1 print (sys.getsizeof(x)) # python3.5中一个32比特的整数占用28字节 |
28
25、使用slots减少内存开支
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import sys # 原始类 class FileSystem( object ): def __init__( self , files, folders, devices): self .files = files self .folder = folders self .devices = devices print (sys.getsizeof(FileSystem)) # 减少内存后 class FileSystem( object ): __slots__ = [ 'files' , 'folders' , 'devices' ] def __init__( self , files, folders, devices): self .files = files self .folder = folders self .devices = devices print (sys.getsizeof(FileSystem)) |
1016
888
26、用lambda 来模仿输出方法
1 2 3 | import sys lprint = lambda * args: sys.stdout.write( " " .join( map ( str , args))) lprint( "python" , "tips" , 1000 , 1001 ) |
python tips 1000 1001
27、从两个相关序列构建一个字典
1 2 3 | t1 = ( 1 , 2 , 3 ) t2 = ( 10 , 20 , 30 ) print ( dict ( zip (t1, t2))) |
{1: 10, 2: 20, 3: 30}
28、搜索字符串的多个前后缀
1 2 | print ( "http://localhost:8888/notebooks/Untitled6.ipynb" .startswith(( "http://" , "https://" ))) print ( "http://localhost:8888/notebooks/Untitled6.ipynb" .endswith(( ".ipynb" , ".py" ))) |
True
True
29、不使用循环构造一个列表
1 2 3 4 | import itertools import numpy as np test = [[ - 1 , - 2 ], [ 30 , 40 ], [ 25 , 35 ]] print ( list (itertools.chain.from_iterable(test))) |
[-1, -2, 30, 40, 25, 35]
30、实现switch-case语句
1 2 3 4 5 | def xswitch(x): return xswitch._system_dict.get(x, None ) xswitch._system_dict = { "files" : 10 , "folders" : 5 , "devices" : 2 } print (xswitch( "default" )) print (xswitch( "devices" )) |
None