[转]Python程序员必须知道的30条编程技巧
30 tips & tricks for Python Programming
1 直接交换两个数字位置
x, y = 10, 20
print(x, y)
x, y = y, x
print(x, y)
#1 (10, 20)
#2 (20, 10)
2 比较运算符的链接
n = 10
result = 1 < n < 20
print(result)
# True
result = 1 > n <= 9
print(result)
# False
3 在条件语句中使用三元运算符
1 [on_true] if [expression] else [on_false]
这样可以使你的代码紧凑和简明。
x = 10 if (y == 9) else 20
同时,我们也可以在类对象中使用。
x = (classA if y == 1 else classB)(param1, param2)
在上面的例子中,有两个类分别是类A和类B,其中一个类的构造函数将会被访问。下面的例子加入了评估最小数的条件。
def small(a, b, c):
return a if a <= b and a <= c else (b if b <= a and b <= c else c) print(small(1, 0, 1))
print(small(1, 2, 2))
print(small(2, 2, 3))
print(small(5, 4, 3)) #Output
#0 #1 #2 #3
我们甚至可以在一个列表生成器中使用三元运算符。
[m**2 if m > 10 else m**4 for m in range(50)] #=> [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)
multiStr = "select * from multi_row \
where row_id < 5"
print(multiStr) # select * from multi_row where row_id < 5
这样做的问题就是没有适当的缩进,如果缩进的话将会使空格也包含在字符串中,所以最终的解决方案就是把字符串分割成多行,把每行字符串放在引号中,然后将它们放在中括号中,如下:
multiStr= ("select * from multi_row "
"where row_id < 5 "
"order by age")
print(multiStr)
5 # select * from multi_row where row_id < 5 order by age
5 在列表中存储变量
我们可以只用列表来初始化多个变量,拆开列表时,变量的数不应超过列表中元素的个数。
testList = [1,2,3]
x, y, z = testList print(x, y, z) #-> 1 2 3
6 打印引入模块的文件路径
import threading
import socket print(threading)
print(socket) #1- <module 'threading' from '/usr/lib/python2.7/threading.py'>
#2- <module 'socket' from '/usr/lib/python2.7/socket.py'>
7 python的IDLE的交互式功能“_”
>>> 2 + 1
3
>>> _
3
>>> print _
3
_下划线输出上次打印的结果
8 字典/集合生成器
testDict = {i: i * i for i in xrange(10)}
testSet = {i * 2 for i in xrange(10)}
print(testSet)
print(testDict)
#set([0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
#{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
9 调试脚本
我们可以使用pdb模块来为我们的脚本设置断点。
import pdb
pdb.set_trace()
10 设置文件共享
Python允许你启动一个HTTP服务,你可以在服务的根目录中共享文件。
# PYTHON 2
python -m SimpleHTTPServer
# PYTHON 3
python3 -m http.server
服务将启动默认的8000端口,你也可以在上面的命令中最后加上一个参数来自定义端口。
11 在Python中检查对象
简单的说就是使用dir()方法,用这个方法来查看这个对象的所有方法。
test = [1, 3, 5, 7]
print( dir(test) )
['__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条件语句
为了验证多个值,我们可以试试一下方法:
使用
if m in [1,3,5,7]:
而不是
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版本
import sys #Detect the Python version currently in use.
if not hasattr(sys, "hexversion") or sys.hexversion != 50660080:
print("Sorry, you aren't running on Python 3.5\n")
print("Please upgrade to 3.5.\n")
sys.exit(1) #Print Python version in a readable format.
print("Current Python version: ", sys.version)
上面的代码中,你可以使用sys.version_info >= (3, 5)来代替sys.hexversion != 50660080。
当运行在Python2.7中时:
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] on linux Sorry, you aren't running on Python 3.5 Please upgrade to 3.5.
当运行在Python3.5上时:
Python 3.5.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux Current Python version: 3.5.2 (default, Aug 22 2016, 21:11:05)
[GCC 5.3.0]
14 结合多个字符串
test = ['I', 'Like', 'Python', 'automation']
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 枚举器
testlist = [10, 20, 30]
for i, value in enumerate(testlist):
print(i, ': ', value) #1-> 0 : 10
#2-> 1 : 20
#3-> 2 : 30
17 使用枚举
class Shapes:
Circle, Square, Triangle, Quadrangle = range(4) print(Shapes.Circle)
print(Shapes.Square)
print(Shapes.Triangle)
print(Shapes.Quadrangle) #1-> 0
#2-> 1
#3-> 2
#4-> 3
18 从函数中返回多个值
# function returning multiple values.
def x():
return 1, 2, 3, 4 # Calling the above function.
a, b, c, d = x() print(a, b, c, d) #-> 1 2 3 4
19 使用星号运算符解包函数参数
def test(x, y, z):
print(x, y, z) testDict = {'x': 1, 'y': 2, 'z': 3}
testList = [10, 20, 30] test(*testDict)
test(**testDict)
test(*testList) #1-> x y z
#2-> 1 2 3
#3-> 10 20 30
20 使用字典来存储表达式
stdcalc = {
'sum': lambda x, y: x + y,
'subtract': lambda x, y: x - y
}
print(stdcalc['sum'](9,3))
print(stdcalc['subtract'](9,3))
#1-> 12
#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 在列表中找到出现次数最多的元素
test = [1,2,3,4,2,2,3,1,4,4,4]
print(max(set(test), key=test.count)) #-> 4
23 重置递归次数限制
import sys x=1001
print(sys.getrecursionlimit()) sys.setrecursionlimit(x)
print(sys.getrecursionlimit()) #1-> 1000
#2-> 1001
24 检查对象的内存使用
#IN PYTHON 2.7.
import sys
x=1
print(sys.getsizeof(x)) #-> 24 #IN PYTHON 3.5.
import sys
x=1
print(sys.getsizeof(x)) #-> 28
25 使用 __slot__ 来减少内存开支
import sys
class FileSystem(object): def __init__(self, files, folders, devices):
self.files = files
self.folders = folders
self.devices = devices print(sys.getsizeof( FileSystem )) class FileSystem1(object): __slots__ = ['files', 'folders', 'devices'] def __init__(self, files, folders, devices):
self.files = files
self.folders = folders
self.devices = devices print(sys.getsizeof( FileSystem1 )) #In Python 3.5
#1-> 1016
#2-> 888
显然,从结果中可以看到内存使用中有节省。但是你应该用__slots__当一个类的内存开销过大。只有在分析应用程序后才能做。否则,你会使代码难以改变,并没有真正的好处。
26 使用lambda处理打印
import sys
lprint=lambda *args:sys.stdout.write(" ".join(map(str,args)))
lprint("python", "tips",1000,1001) #-> python tips 1000 1001
27 通过两个相关序列创建字典
t1 = (1, 2, 3)
t2 = (10, 20, 30) print(dict (zip(t1,t2))) #-> {1: 10, 2: 20, 3: 30}
28 搜索多个前缀后缀字符串
print("http://www.google.com".startswith(("http://", "https://")))
print("http://www.google.co.uk".endswith((".com", ".co.uk")))
#1-> True
#2-> True
29 不使用任何循环形成一个统一的列表
import itertools
test = [[-1, -2], [30, 40], [25, 35]]
print(list(itertools.chain.from_iterable(test))) #-> [-1, -2, 30, 40, 25, 35]
30 在Python中实现一个真正的切换实例声明
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')) #1-> None
#2-> 2
转载翻译自http://www.techbeamers.com/essential-python-tips-tricks-programmers/
[转]Python程序员必须知道的30条编程技巧的更多相关文章
- Java程序员必须知道的10个调试技巧
调试可以帮助识别和解决应用程序缺陷,在本文中,将使用大家常用的的开发工具Eclipse来调试Java应用程序. 但这里介绍的调试方法基本都是通用的,也适用于NetBeans IDE,我们会把重点放在运 ...
- CakePHP程序员必须知道的21条技巧
这篇文章可以说是CakePHP 教程中最经典的了.虽然不是完整的手把手系列, 但作者将自己使用CakePHP 的经验总结了21条,这些尤其是对新手十分有用. 翻译时故意保留了一些CakePHP 中特有 ...
- 程序员必须知道的HTML常用代码有哪些?
HTML即超文本标记语言,是目前应用最为广泛的语言之一,是组成一个网页的主要语言.在现今这个HTML5华丽丽地占领了整个互联网的时候,如果想要通过网页抓住浏览者的眼球光靠因循守旧是不行的,程序猿们需要 ...
- (转载) 据说年薪30万的Android程序员必须知道的
据说年薪30万的Android程序员必须知道的帖子 标签: android 2015-03-12 16:52 28705人阅读 评论(14) 收藏 举报 Android中国开发精英 目前包括: And ...
- 程序员必须知道的git托管平台
http://www.open-open.com/lib/view/open1420704561390.html
- (转)Java程序员应该知道的10个调试技巧
(转自 酷勤网 – 程序员的那点事!http://www.kuqin.com/) 试可以帮助识别和解决应用程序缺陷,在本文中,作者将使用大家常用的的开发工具Eclipse来调试Java应用程序.但这里 ...
- 程序员必需知道的Mac OS使用技巧
macos sierra正式版发布了,于是我把我沉寂了一年没有用过了的macbook拿出来玩玩,顺便把一些常用技巧mark. 1.apple store下载软件无响应(经常出现的问题) 解决方法:更改 ...
- 学python必须知道的30个技巧
收集这些有用的捷径技巧 1. 原地进行交换两个数字 我们对赋值的右侧进行一个新的元组,左侧解析(unpack)那个(未被引用的)元组到变量 <a> 和 <b> 赋值完成时,新的 ...
- App运营者必须知道的30款数据分析工具
如今的移动应用早已不再是某种结构单一.功能简单的工具了.当我们的移动应用变得越来越庞杂,我们便会需要借用分析工具,来跟踪和分析App内的每一个部分.幸运的是,目前市面上有许多数据分析工具可供App开发 ...
随机推荐
- CodeBlocks配置pthread环境
参考资料:MinGW配置pthread环境 按[参考资料]里说的[下载资源]后,将libpthreadGC2.a放到codeBlocks安装目录下的MinGW\lib目录下,然后将pthread.h ...
- [转载]: delphi中XLSReadWrite控件的使用(3)---基本应用
这是自带的一个例子,看懂这一点东西,基本的操作应该没问题了.... unit Main; interface uses Windows, Messages, SysUtils, Variants, C ...
- nohup输入密码后继续后台运行
Linux/Unix 是真正的多用户,多任务.Linux 提供了 fg 和bg 命令,让你轻松调度正在运行的任务. 假设你发现前台运行的一个程序需要很长的时间,但是需要干其他的事情,你就可以用 Ctr ...
- React学习之一:React初探
一,React简介 React是由Facebook和Instagram开发的一套创建用户界面的JavaScript库.许多人认为React是MVC中的V. React创建的目的是为了:构建数据随时会改 ...
- AIX系统程序异常不释放光驱处理
AIX操作系统有时会出现程序异常不释放光驱,可以用以下命令进行处理: #fuser -kxuc /dev/cd0 或者 #fuser /dev/cd0 以上命令会列出访问光驱设备的所有进程,然后使用k ...
- .NET高级工程师面试题之SQL篇
1 题目 这确实是一个真实的面试题,琢磨一下吧!知识不用,就会丢掉,我太依赖各种框架和dll了,已经忘记了最基本的东西.有多久没有写过SQL了,我已经不记得了. 已知表信息如下: Department ...
- 安装mysql5.5时候的报错解决办法:
每次安装mysql5.5的时候总会报出一下错误: -- Could NOT find OpenSSL (missing: OPENSSL_LIBRARIES OPENSSL_INCLUDE_DIR) ...
- hibernate学习(设计一对多 关系 映射)
1,配置文件: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-conf ...
- HttpClient请求发送的几种用法:
/// <summary> /// HttpClient实现Post请求 /// </summary> static async void dooPost() { string ...
- Python3 多线程下载代码
根据http://www.oschina.net/code/snippet_70229_2407修改而来的增强版.貌似原版源自Axel这个多线程下载工具. ''' Created on 2014-10 ...