Python代码编写中的性能优化点
1. 交换赋值
##不推荐
temp = a
a = b
b = a ##推荐
a, b = b, a # 先生成一个元组(tuple)对象,然后unpack
2. Unpacking
##不推荐
l = ['David', 'Pythonista', '+1-514-555-1234']
first_name = l[0]
last_name = l[1]
phone_number = l[2] ##推荐
l = ['David', 'Pythonista', '+1-514-555-1234']
first_name, last_name, phone_number = l
# Python 3 Only
first, *middle, last = another_list
3. 使用操作符in
##不推荐
if fruit == "apple" or fruit == "orange" or fruit == "berry":# 多次判断 ##推荐
if fruit in ["apple", "orange", "berry"]:# 使用 in 更加简洁
4. 字符串操作
##不推荐
colors = ['red', 'blue', 'green', 'yellow']result = ''
for s in colors:result += s # 每次赋值都丢弃以前的字符串对象, 生成一个新对象 ##推荐
colors = ['red', 'blue', 'green', 'yellow']
result = ''.join(colors) # 没有额外的内存分配
5. 字典键值列表
##不推荐
for key in my_dict.keys():# my_dict[key] ... ##推荐
for key in my_dict:# my_dict[key] ...# 只有当循环中需要更改key值的情况下,我们需要使用 my_dict.keys()
# 生成静态的键值列表。
6. 字典键值判断
##不推荐
if my_dict.has_key(key):# ...do something with d[key] ##推荐
if key in my_dict:# ...do something with d[key]
7. 字典 get 和 setdefault 方法
##不推荐
navs = {}
for (portfolio, equity, position) in data:if portfolio not in navs:navs[portfolio] = 0navs[portfolio] += position * prices[equity]
##推荐
navs = {}
for (portfolio, equity, position) in data:# 使用 get 方法navs[portfolio] = navs.get(portfolio, 0) + position * prices[equity]# 或者使用 setdefault 方法navs.setdefault(portfolio, 0)navs[portfolio] += position * prices[equity]
8. 判断真伪
##不推荐
if x == True:# ....
if len(items) != 0:# ...
if items != []:# ... ##推荐
if x:# ....
if items:# ...
9. 遍历列表以及索引
##不推荐
items = 'zero one two three'.split()
# method 1
i = 0
for item in items:print i, itemi += 1
# method 2
for i in range(len(items)):print i, items[i]##推荐
items = 'zero one two three'.split()
for i, item in enumerate(items):print i, item
10. 列表推导
##不推荐
new_list = []
for item in a_list:if condition(item):new_list.append(fn(item)) ##推荐
new_list = [fn(item) for item in a_list if condition(item)]
11. 列表推导-嵌套
##不推荐
for sub_list in nested_list:if list_condition(sub_list):for item in sub_list:if item_condition(item):# do something...
##推荐
gen = (item for sl in nested_list if list_condition(sl) \for item in sl if item_condition(item))
for item in gen:# do something...
12. 循环嵌套
##不推荐
for x in x_list:for y in y_list:for z in z_list:# do something for x & y ##推荐
from itertools import product
for x, y, z in product(x_list, y_list, z_list):# do something for x, y, z
13. 尽量使用生成器代替列表
##不推荐
def my_range(n):i = 0result = []while i < n:result.append(fn(i))i += 1return result # 返回列表##推荐
def my_range(n):i = 0result = []while i < n:yield fn(i) # 使用生成器代替列表i += 1
*尽量用生成器代替列表,除非必须用到列表特有的函数。
14. 中间结果尽量使用imap/ifilter代替map/filter
##不推荐
reduce(rf, filter(ff, map(mf, a_list)))##推荐
from itertools import ifilter, imap
reduce(rf, ifilter(ff, imap(mf, a_list)))
*lazy evaluation 会带来更高的内存使用效率,特别是当处理大数据操作的时候。
15. 使用any/all函数
##不推荐
found = False
for item in a_list:if condition(item):found = Truebreak
if found:# do something if found... ##推荐
if any(condition(item) for item in a_list):# do something if found...
16. 属性(property)
=##不推荐
class Clock(object):def __init__(self):self.__hour = 1def setHour(self, hour):if 25 > hour > 0: self.__hour = hourelse: raise BadHourExceptiondef getHour(self):return self.__hour##推荐
class Clock(object):def __init__(self):self.__hour = 1def __setHour(self, hour):if 25 > hour > 0: self.__hour = hourelse: raise BadHourExceptiondef __getHour(self):return self.__hourhour = property(__getHour, __setHour)
17. 使用 with 处理文件打开
##不推荐
f = open("some_file.txt")
try:data = f.read()# 其他文件操作..
finally:f.close()##推荐
with open("some_file.txt") as f:data = f.read()# 其他文件操作...
18. 使用 with 忽视异常(仅限Python 3)
##不推荐
try:os.remove("somefile.txt")
except OSError:pass##推荐
from contextlib import ignored # Python 3 onlywith ignored(OSError):os.remove("somefile.txt")
19. 使用 with 处理加锁
##不推荐
import threading
lock = threading.Lock()lock.acquire()
try:# 互斥操作...
finally:lock.release()##推荐
import threading
lock = threading.Lock()with lock:# 互斥操作...
来源:微信
转载于:https://blog.51cto.com/10412806/2280887
Python代码编写中的性能优化点相关推荐
- python代码编写_高质量Python代码编写的5个优化技巧
如今我使用 Python 已经很长时间了,但当我回顾之前写的一些代码时,有时候会感到很沮丧.例如,最早使用 Python 时,我写了一个名为 Sudoku 的游戏(GitHub地址:https://g ...
- python代码编写工具_编写更好的Python代码的终极指南
python代码编写工具 Despite its 尽管它 downsides, Python remains the king of today's programming world. Its ve ...
- [python]用profile协助程序性能优化
本文最初发表于恋花蝶的博客http://blog.csdn.net/lanphaday,欢迎转载,但请务必保留原文完整,并保留本声明. [python]用profile协助程序性能优化 上帝说:&qu ...
- Python代码编写过程中有哪些重要技巧?
近几年,转行做Python技术岗的人越来越多,大家对于Python的关注越来越高,尤其是工作后,很多人都想知道Python代码编写过程中有哪些重要技巧?小编告诉大家,在编写Python代码过程中,除了 ...
- [转]游戏中各种性能优化方法(不断更新)
http://www.cppblog.com/liangairan/archive/2013/03/23/198749.aspx 谈到游戏中的性能优化,说白了就是如何提高帧率和降低内存. 提高帧率的基 ...
- Go在迅雷P2P连通系统中的性能优化实践-朱文
目 录 1. 如何构建压测环境 2. 如何分析性能瓶颈 3. 如何做性能优化 语言层面 设计层面 4. 总结 主要内容 我是来自迅雷的后台开发架构师,今天很高兴给大家分享一下我在迅雷连通系统中的性能优 ...
- python9行代码_如何用9行Python代码编写一个简易神经网络
原标题:如何用9行Python代码编写一个简易神经网络 Python部落(python.freelycode.com)组织翻译,禁止转载,欢迎转发. 学习人工智能时,我给自己定了一个目标--用Pyth ...
- 微课|中学生可以这样学Python(1.3节):Python代码编写规范
适用教材: 董付国,应根球.<中学生可以这样学Python>.清华大学出版社,2017. 第1章 Python概述 1.3 Python代码编写规范 京东购买链接:https://it ...
- 谈谈VR游戏中的性能优化
VR游戏相对传统游戏,个人认为主要有三个方面的不同:玩法设计,输入方式,性能压力.今天就来谈一下VR游戏中的性能优化. 为什么VR游戏的性能压力很大? ·主要有三个因素的影响:高帧率,高分辨率,画两遍 ...
最新文章
- 2021年春季学期-信号与系统-第十次作业参考答案-第一小题
- 网页中获取微信用户是否关注订阅号的思路
- 我的Android进阶之旅------Android中高低API版本兼容使用@TargetApi或者@SuppressLint(NewApi)...
- antd 设置表头属性_解决react使用antd table组件固定表头后,表头和表体列不对齐以及配置fixed固定左右侧后行高度不对齐...
- Solr7.3 Cloud On HDFS搭建
- HNU 程序设计课 函数公式题
- 2020-5-9 开始阅读深入理解java虚拟机
- js中字符串类转为日期类,并比较
- Adobe放出P图新研究:就算丢了半个头,也能逼真复原
- NLP工具包(Albert+BiLSTM+CRF)
- GitLab容器注册服务已集成于Docker容器
- android 7 audio架构,7.2.1 Audio系统的各个层次
- 算法:罗马数字转换为整数13. Roman to Integer
- Z=X+Y型概率密度的求解
- HTML5 学习总结(一)——HTML5概要与新增标签
- AI三大主义:符号主义、联结主义、行为主义
- 【C++学习笔记】类型转换和跳转语句
- curl检测网页的用法
- problem 1278
- 【git系列004】解决 git 未指定冲突处理方法的问题
热门文章
- head tail mkdir cp
- [SPOJ705]不同的子串
- 体验Office 2013预览版
- 180508 - 解决有关VIVO的2018-04-01安全补丁导致的APP闪退问题
- (十五)Java springcloud B2B2C o2o多用户商城 springcloud架构-commonservice-sso服务搭建(一)...
- Mysql关闭和修改密码
- boost::asio::streambuf 基本用法和注意事项
- 使用Markdown写作
- npm安装bower时报错 我已解决
- (三)spark集群DHCP IP变化后的处理