Python程序员需要知道的30个技巧

简介:

1  直接交换两个数字位置

1x, y = 10, 202print(x, y)3x, y = y, x4print(x, y)5#1 (10, 20)6#2 (20, 10)

2  比较运算符的链接

1n = 102result = 1 < n < 203print(result)4# True5result = 1 > n <= 96print(result)7# False

3  在条件语句中使用三元运算符

1 [on_true]if[expression]else[on_false]

这样可以使你的代码紧凑和简明。

1x = 10if(y == 9)else20

同时,我们也可以在类对象中使用。

1x = (classAify == 1elseclassB)(param1, param2)

在上面的例子中,有两个类分别是类A和类B,其中一个类的构造函数将会被访问。下面的例子加入了评估最小数的条件。

1def small(a, b, c): 2returnaifa <= banda <= celse(bifb <= aandb <= celse c) 3 4print(small(1, 0, 1)) 5print(small(1, 2, 2)) 6print(small(2, 2, 3)) 7print(small(5, 4, 3)) 8 9#Output10#0 #1 #2 #3

我们甚至可以在一个列表生成器中使用三元运算符。

1[m**2ifm > 10elsem**4forminrange(50)]23#=> [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)

1multiStr ="select * from multi_row \2where row_id < 5"3print(multiStr)45#select * from multi_row where row_id < 5

这样做的问题就是没有适当的缩进,如果缩进的话将会使空格也包含在字符串中,所以最终的解决方案就是把字符串分割成多行,把每行字符串放在引号中,然后将它们放在中括号中,如下:

1multiStr= ("select * from multi_row "2"where row_id < 5 "3"order by age")4print(multiStr)

5# select * from multi_row where row_id < 5 order by age

5  在列表中存储变量

我们可以只用列表来初始化多个变量,拆开列表时,变量的数不应超过列表中元素的个数。

1testList = [1,2,3]2x, y, z = testList34print(x, y, z)56#-> 1 2 3

6  打印引入模块的文件路径

1import threading 2import socket34print(threading)5print(socket)67#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 + 1233>>> _435>>>print _63

_下划线输出上次打印的结果

在学习中有迷茫不知如何学习的朋友小编推荐一个学Python的学习q u n 227  -435-  450可以来了解一起进步一起学习!免费分享视频资料

8  字典/集合生成器

1testDict = {i: i * iforiinxrange(10)} 2testSet = {i * 2foriinxrange(10)}34print(testSet)5print(testDict)67#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模块来为我们的脚本设置断点。

1import pdb2pdb.set_trace()

10  设置文件共享

Python允许你启动一个HTTP服务,你可以在服务的根目录中共享文件。

1# PYTHON 22python -m SimpleHTTPServer3# PYTHON 34python3 -m http.server

服务将启动默认的8000端口,你也可以在上面的命令中最后加上一个参数来自定义端口。

11  在Python中检查对象

简单的说就是使用dir()方法,用这个方法来查看这个对象的所有方法。

1test = [1, 3, 5, 7]2print( 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使用2ifmin[1,3,5,7]:3而不是4ifm==1orm==3orm==5orm==7:

作为选择,我们可以在‘in’运算符后面使用‘{1,3,5,7}’代替‘[1,3,5,7]’因为 ‘set’ can access each element by O(1)。

13  在运行时检测Python版本

1import sys 2 3#Detect the Python version currently in use. 4ifnothasattr(sys,"hexversion")orsys.hexversion != 50660080: 5print("Sorry, you aren't running on Python 3.5\n") 6print("Please upgrade to 3.5.\n") 7sys.exit(1) 8 9#Print Python version in a readable format.10print("Current Python version: ", sys.version)

上面的代码中,你可以使用sys.version_info >= (3, 5)来代替sys.hexversion != 50660080。

当运行在Python2.7中时:

1Python 2.7.10 (default, Jul 14 2015, 19:46:27)2[GCC 4.8.2] on linux34Sorry, you aren't running on Python 3.556Please upgrade to 3.5.

当运行在Python3.5上时:

1Python 3.5.1 (default, Dec 2015, 13:05:11)2[GCC 4.8.2] on linux34Current Python version:  3.5.2 (default, Aug 22 2016, 21:11:05) 5[GCC 5.3.0]

14 结合多个字符串

1test = ['I','Like','Python','automation']2print''.join(test)

15  万能的逆转机制

#逆转列表testList = [1, 3, 5]

testList.reverse()print(testList)

#-> [5, 3, 1]#在一个循环中反向迭代forelementinreversed([1,3,5]):print(element)

#1-> 5#2-> 3#3-> 1#字符串"Test Python"[::-1]#使用切片反向列表[1, 3, 5][::-1]

16  枚举器

1testlist = [10, 20, 30]2fori, valuein enumerate(testlist):3print(i,': ', value)45#1-> 0 : 106#2-> 1 : 207#3-> 2 : 30

17  使用枚举

1class Shapes: 2Circle, Square, Triangle, Quadrangle = range(4) 3 4print(Shapes.Circle) 5print(Shapes.Square) 6print(Shapes.Triangle) 7print(Shapes.Quadrangle) 8 9#1-> 010#2-> 111#3-> 212#4-> 3

18  从函数中返回多个值

1# function returning multiple values. 2def x(): 3return1, 2, 3, 4 4 5# Calling the above function. 6a, b, c, d = x() 7 8print(a, b, c, d) 910#-> 1 2 3 4

19  使用星号运算符解包函数参数

1def test(x, y, z): 2print(x, y, z) 3 4testDict = {'x': 1,'y': 2,'z': 3}  5testList = [10, 20, 30] 6 7test(*testDict) 8test(**testDict) 9test(*testList)1011#1-> x y z12#2-> 1 2 313#3-> 10 20 30

20  使用字典来存储表达式

1stdcalc = { 2'sum':lambdax, y: x + y, 3'subtract':lambdax, y: x - y 4} 5 6print(stdcalc['sum'](9,3)) 7print(stdcalc['subtract'](9,3)) 8 9#1-> 1210#2-> 6

21  在任意一行数字中计算阶乘

#PYTHON 2.X.result = (lambdak: reduce(int.__mul__, range(1,k+1),1))(3)print(result)#-> 6#PYTHON 3.X.import functools

result = (lambdak: functools.reduce(int.__mul__, range(1,k+1),1))(3)print(result)

#-> 6

22  在列表中找到出现次数最多的元素

1test = [1,2,3,4,2,2,3,1,4,4,4]2print(max(set(test), key=test.count))34#-> 4

23  重置递归次数限制

1import sys 2 3x=1001 4print(sys.getrecursionlimit()) 5 6sys.setrecursionlimit(x) 7print(sys.getrecursionlimit()) 8 9#1-> 100010#2-> 1001

24  检查对象的内存使用

1#IN PYTHON 2.7. 2import sys 3x=1 4print(sys.getsizeof(x)) 5 6#-> 24 7 8#IN PYTHON 3.5. 9import sys10x=111print(sys.getsizeof(x))1213#-> 28

25  使用 __slot__ 来减少内存开支

1import sys 2class FileSystem(object): 3 4def__init__(self, files, folders, devices): 5self.files = files 6self.folders = folders 7self.devices = devices 8 9print(sys.getsizeof( FileSystem ))1011class FileSystem1(object):1213__slots__= ['files','folders','devices']1415def__init__(self, files, folders, devices):16self.files = files17self.folders = folders18self.devices = devices1920print(sys.getsizeof( FileSystem1 ))2122#In Python 3.523#1-> 101624#2-> 888

显然,从结果中可以看到内存使用中有节省。但是你应该用__slots__当一个类的内存开销过大。只有在分析应用程序后才能做。否则,你会使代码难以改变,并没有真正的好处。

26  使用lambda处理打印

1import sys2lprint=lambda*args:sys.stdout.write("".join(map(str,args)))3lprint("python","tips",1000,1001)45#-> python tips 1000 1001

27  通过两个相关序列创建字典

1t1 = (1, 2, 3)2t2 = (10, 20, 30)34print(dict (zip(t1,t2)))56#-> {1: 10, 2: 20, 3: 30}

28  搜索多个前缀后缀字符串

1print("http://www.google.com".startswith(("http://","https://")))2print("http://www.google.co.uk".endswith((".com",".co.uk")))34#1-> True5#2-> True

29  不使用任何循环形成一个统一的列表

1import itertools2test = [[-1, -2], [30, 40], [25, 35]]3print(list(itertools.chain.from_iterable(test)))45#-> [-1, -2, 30, 40, 25, 35]

30  在Python中实现一个真正的切换实例声明

1def xswitch(x):  2return xswitch._system_dict.get(x, None)  3 4xswitch._system_dict = {'files': 10,'folders': 5,'devices': 2} 5 6print(xswitch('default')) 7print(xswitch('devices')) 8 9#1-> None10#2-> 2

相关文章
|
1月前
|
存储 缓存 程序员
Python程序员Debug利器,和Print说再见
Python程序员Debug利器,和Print说再见
25 2
|
8月前
|
程序员 Python
中秋节之Python绘制许愿树和月饼(打开程序员世界的大门)
中秋节之Python绘制许愿树和月饼(打开程序员世界的大门)
|
2月前
|
程序员 C语言 Python
[oeasy]python0007_ print函数_字符串_display_电传打字机_程序员的浪漫
[oeasy]python0007_ print函数_字符串_display_电传打字机_程序员的浪漫
37 5
[oeasy]python0007_ print函数_字符串_display_电传打字机_程序员的浪漫
|
3月前
|
存储 程序员 数据处理
Python文件操作与数据持久化:解放程序员的存储之道
在当今大数据时代,程序员需要处理大量的数据,并确保数据的安全和持久性。本文将介绍Python中强大的文件操作功能和数据持久化技术,帮助程序员更好地管理和存储数据,提高工作效率和数据处理能力。
18 1
|
4月前
|
程序员 Python
每个新手程序员都应该知道的 Python 技巧
每个新手程序员都应该知道的 Python 技巧
|
8月前
|
安全 程序员 开发工具
代码版本管理笔记 | Python 程序员也应该会的 Git 分支操作
代码版本管理笔记 | Python 程序员也应该会的 Git 分支操作
127 0
|
8月前
|
数据采集 安全 JavaScript
代码版本管理笔记 | Python 程序员也应该会的 Git 进阶操作
代码版本管理笔记 | Python 程序员也应该会的 Git 进阶操作
118 0
|
8月前
|
数据采集 缓存 安全
代码版本管理笔记 | Python 程序员也应该会的 Git 基础操作
代码版本管理笔记 | Python 程序员也应该会的 Git 基础操作
|
9月前
|
Web App开发 数据采集 算法
【我问Crossin】学会 Python 离成为一名程序员还差多远?
使用 selenium 连接 chrome 或者 firfox 等浏览器,模拟登陆、点击视频等操作。
|
10月前
|
Java 程序员 Python
十个Python程序员易犯的错误
十个Python程序员易犯的错误