[转]Python程序员必须知道的30条编程技巧
30 tips & tricks for Python Programming
1 直接交换两个数字位置
1 x, y = 10, 20 2 print(x, y) 3 x, y = y, x 4 print(x, y) 5 #1 (10, 20) 6 #2 (20, 10)
2 比较运算符的链接
1 n = 10 2 result = 1 < n < 20 3 print(result) 4 # True 5 result = 1 > n <= 9 6 print(result) 7 # False
3 在条件语句中使用三元运算符
1 [on_true] if [expression] else [on_false]
这样可以使你的代码紧凑和简明。
1 x = 10 if (y == 9) else 20
同时,我们也可以在类对象中使用。
1 x = (classA if y == 1 else classB)(param1, param2)
在上面的例子中,有两个类分别是类A和类B,其中一个类的构造函数将会被访问。下面的例子加入了评估最小数的条件。
1 def small(a, b, c): 2 return a if a <= b and a <= c else (b if b <= a and b <= c else c) 3 4 print(small(1, 0, 1)) 5 print(small(1, 2, 2)) 6 print(small(2, 2, 3)) 7 print(small(5, 4, 3)) 8 9 #Output 10 #0 #1 #2 #3
我们甚至可以在一个列表生成器中使用三元运算符。
1 [m**2 if m > 10 else m**4 for m in range(50)] 2 3 #=> [0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729 , 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]
4 多行字符串
使用反斜杠(backslashes)的基本方法最初来源于c语言,当然,我们熟悉的方法是使用三个引号(triple-quotes)
1 multiStr = "select * from multi_row \ 2 where row_id < 5" 3 print(multiStr) 4 5 # select * from multi_row where row_id < 5
这样做的问题就是没有适当的缩进,如果缩进的话将会使空格也包含在字符串中,所以最终的解决方案就是把字符串分割成多行,把每行字符串放在引号中,然后将它们放在中括号中,如下:
1 multiStr= ("select * from multi_row " 2 "where row_id < 5 " 3 "order by age") 4 print(multiStr)
5 # select * from multi_row where row_id < 5 order by age
5 在列表中存储变量
我们可以只用列表来初始化多个变量,拆开列表时,变量的数不应超过列表中元素的个数。
1 testList = [1,2,3] 2 x, y, z = testList 3 4 print(x, y, z) 5 6 #-> 1 2 3
6 打印引入模块的文件路径
1 import threading 2 import socket 3 4 print(threading) 5 print(socket) 6 7 #1- <module 'threading' from '/usr/lib/python2.7/threading.py'> 8 #2- <module 'socket' from '/usr/lib/python2.7/socket.py'>
7 python的IDLE的交互式功能“_”
1 >>> 2 + 1 2 3 3 >>> _ 4 3 5 >>> print _ 6 3
_下划线输出上次打印的结果
8 字典/集合生成器
1 testDict = {i: i * i for i in xrange(10)} 2 testSet = {i * 2 for i in xrange(10)} 3 4 print(testSet) 5 print(testDict) 6 7 #set([0, 2, 4, 6, 8, 10, 12, 14, 16, 18]) 8 #{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
9 调试脚本
我们可以使用pdb模块来为我们的脚本设置断点。
1 import pdb 2 pdb.set_trace()
10 设置文件共享
Python允许你启动一个HTTP服务,你可以在服务的根目录中共享文件。
1 # PYTHON 2 2 python -m SimpleHTTPServer 3 # PYTHON 3 4 python3 -m http.server
服务将启动默认的8000端口,你也可以在上面的命令中最后加上一个参数来自定义端口。
11 在Python中检查对象
简单的说就是使用dir()方法,用这个方法来查看这个对象的所有方法。
1 test = [1, 3, 5, 7] 2 print( dir(test) ) 3 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
12 简化if条件语句
为了验证多个值,我们可以试试一下方法:
1 使用 2 if m in [1,3,5,7]: 3 而不是 4 if m==1 or m==3 or m==5 or m==7:
作为选择,我们可以在‘in’运算符后面使用‘{1,3,5,7}’代替‘[1,3,5,7]’因为 ‘set’ can access each element by O(1)。
13 在运行时检测Python版本
1 import sys 2 3 #Detect the Python version currently in use. 4 if not hasattr(sys, "hexversion") or sys.hexversion != 50660080: 5 print("Sorry, you aren't running on Python 3.5\n") 6 print("Please upgrade to 3.5.\n") 7 sys.exit(1) 8 9 #Print Python version in a readable format. 10 print("Current Python version: ", sys.version)
上面的代码中,你可以使用sys.version_info >= (3, 5)来代替
sys.hexversion != 50660080。
当运行在Python2.7中时:
1 Python 2.7.10 (default, Jul 14 2015, 19:46:27) 2 [GCC 4.8.2] on linux 3 4 Sorry, you aren't running on Python 3.5 5 6 Please upgrade to 3.5.
当运行在Python3.5上时:
1 Python 3.5.1 (default, Dec 2015, 13:05:11) 2 [GCC 4.8.2] on linux 3 4 Current Python version: 3.5.2 (default, Aug 22 2016, 21:11:05) 5 [GCC 5.3.0]
14 结合多个字符串
1 test = ['I', 'Like', 'Python', 'automation'] 2 print ''.join(test)
15 万能的逆转机制
#逆转列表 testList = [1, 3, 5] testList.reverse() print(testList) #-> [5, 3, 1] #在一个循环中反向迭代 for element in reversed([1,3,5]): print(element) #1-> 5 #2-> 3 #3-> 1 #字符串 "Test Python"[::-1] #使用切片反向列表 [1, 3, 5][::-1]
16 枚举器
1 testlist = [10, 20, 30] 2 for i, value in enumerate(testlist): 3 print(i, ': ', value) 4 5 #1-> 0 : 10 6 #2-> 1 : 20 7 #3-> 2 : 30
17 使用枚举
1 class Shapes: 2 Circle, Square, Triangle, Quadrangle = range(4) 3 4 print(Shapes.Circle) 5 print(Shapes.Square) 6 print(Shapes.Triangle) 7 print(Shapes.Quadrangle) 8 9 #1-> 0 10 #2-> 1 11 #3-> 2 12 #4-> 3
18 从函数中返回多个值
1 # function returning multiple values. 2 def x(): 3 return 1, 2, 3, 4 4 5 # Calling the above function. 6 a, b, c, d = x() 7 8 print(a, b, c, d) 9 10 #-> 1 2 3 4
19 使用星号运算符解包函数参数
1 def test(x, y, z): 2 print(x, y, z) 3 4 testDict = {'x': 1, 'y': 2, 'z': 3} 5 testList = [10, 20, 30] 6 7 test(*testDict) 8 test(**testDict) 9 test(*testList) 10 11 #1-> x y z 12 #2-> 1 2 3 13 #3-> 10 20 30
20 使用字典来存储表达式
1 stdcalc = { 2 'sum': lambda x, y: x + y, 3 'subtract': lambda x, y: x - y 4 } 5 6 print(stdcalc['sum'](9,3)) 7 print(stdcalc['subtract'](9,3)) 8 9 #1-> 12 10 #2-> 6
21 在任意一行数字中计算阶乘
#PYTHON 2.X. result = (lambda k: reduce(int.__mul__, range(1,k+1),1))(3) print(result) #-> 6 #PYTHON 3.X. import functools result = (lambda k: functools.reduce(int.__mul__, range(1,k+1),1))(3) print(result) #-> 6
22 在列表中找到出现次数最多的元素
1 test = [1,2,3,4,2,2,3,1,4,4,4] 2 print(max(set(test), key=test.count)) 3 4 #-> 4
23 重置递归次数限制
1 import sys 2 3 x=1001 4 print(sys.getrecursionlimit()) 5 6 sys.setrecursionlimit(x) 7 print(sys.getrecursionlimit()) 8 9 #1-> 1000 10 #2-> 1001
24 检查对象的内存使用
1 #IN PYTHON 2.7. 2 import sys 3 x=1 4 print(sys.getsizeof(x)) 5 6 #-> 24 7 8 #IN PYTHON 3.5. 9 import sys 10 x=1 11 print(sys.getsizeof(x)) 12 13 #-> 28
25 使用 __slot__ 来减少内存开支
1 import sys 2 class FileSystem(object): 3 4 def __init__(self, files, folders, devices): 5 self.files = files 6 self.folders = folders 7 self.devices = devices 8 9 print(sys.getsizeof( FileSystem )) 10 11 class FileSystem1(object): 12 13 __slots__ = ['files', 'folders', 'devices'] 14 15 def __init__(self, files, folders, devices): 16 self.files = files 17 self.folders = folders 18 self.devices = devices 19 20 print(sys.getsizeof( FileSystem1 )) 21 22 #In Python 3.5 23 #1-> 1016 24 #2-> 888
显然,从结果中可以看到内存使用中有节省。但是你应该用__slots__当一个类的内存开销过大。只有在分析应用程序后才能做。否则,你会使代码难以改变,并没有真正的好处。
26 使用lambda处理打印
1 import sys 2 lprint=lambda *args:sys.stdout.write(" ".join(map(str,args))) 3 lprint("python", "tips",1000,1001) 4 5 #-> python tips 1000 1001
27 通过两个相关序列创建字典
1 t1 = (1, 2, 3) 2 t2 = (10, 20, 30) 3 4 print(dict (zip(t1,t2))) 5 6 #-> {1: 10, 2: 20, 3: 30}
28 搜索多个前缀后缀字符串
1 print("http://www.google.com".startswith(("http://", "https://"))) 2 print("http://www.google.co.uk".endswith((".com", ".co.uk"))) 3 4 #1-> True 5 #2-> True
29 不使用任何循环形成一个统一的列表
1 import itertools 2 test = [[-1, -2], [30, 40], [25, 35]] 3 print(list(itertools.chain.from_iterable(test))) 4 5 #-> [-1, -2, 30, 40, 25, 35]
30 在Python中实现一个真正的切换实例声明
1 def xswitch(x): 2 return xswitch._system_dict.get(x, None) 3 4 xswitch._system_dict = {'files': 10, 'folders': 5, 'devices': 2} 5 6 print(xswitch('default')) 7 print(xswitch('devices')) 8 9 #1-> None 10 #2-> 2
转载翻译自http://www.techbeamers.com/essential-python-tips-tricks-programmers/