当前位置:首页 >> 编程语言 >> 【Python】提升Python程序性能的好习惯2,m3a78(python提高程序运行速度)

【Python】提升Python程序性能的好习惯2,m3a78(python提高程序运行速度)

0evadmin 编程语言 2
文件名:【Python】提升Python程序性能的好习惯2,m3a78 【Python】提升Python程序性能的好习惯2

掌握一些技巧,可尽量提高Python程序性能,也可以避免不必要的资源浪费。 追求性能极限是一个有趣的游戏, 而过度优化就会变成嘲弄了。虽然Python授予你与C接口无缝集成的能力, 你必须问自己你花数小时的艰辛优化工作用户是否买帐.  另一方面, 牺牲代码的可维护性换取几毫秒的提升是否值得,团队中的成员常常会感谢你编写了简洁的代码。

上一篇文章提升Python程序性能的好习惯,这篇文章是继续补充一些提升性能的一些技巧

''''''''''''''''''''''''''''''''''''''''# 2019年2月11日 11点00分# 作者:cacho_37967865# 文件:highFunction2.py# 主题:提升Python程序性能的好习惯2'''''''''''''''''''''''''''''''''''''''''import threadingdef high_fun():# 1.如何使用锁lock = threading.Lock() # 创建锁lock.acquire()try:print('使用锁的老方法')finally:lock.release()# 更好的方法with lock:print('使用锁的新方法')# 2.如何打开和关闭文件f = open('F:\\new.txt')try:data = f.read()print(data)finally:f.close()# 更好的方法with open('F:\\new.txt') as f:data = f.read()print('打开文件更好的方法:',data)# 3.连接列表中字符串names = ['raymond', 'rachel', 'matthew', 'roger', 'betty', 'melissa', 'judith', 'charlie']s = names[0]for name in names[1:]:s += ', ' + nameprint(s)# 更好的方法print(', '.join(names))# 4.反向遍历列表colors = ['red', 'green', 'blue', 'yellow']for i in range(len(colors) - 1, -1, -1):print(colors[i])# 更好的方法for color in reversed(colors):print(color)# 5.遍历一个集合及其下标colors = ['red', 'green', 'blue', 'yellow']for i in range(len(colors)):print(i, '--->', colors[i])# 更好的方法for i, color in enumerate(colors):print(i, '-->', colors[i])# 6.遍历两个集合names = ['raymond', 'rachel', 'matthew']colors = ['red', 'green', 'blue', 'yellow']n = min(len(names), len(colors))print("min()函数:",n)for i in range(n):print(names[i], '--->', colors[i])# 更好的方法for name, color in zip(names, colors):print(name, '-->', color)# 7.遍历一个字典的key和valued = {'id': 1,'nick_name': '十语荐书','content': '今日得到:'}# 并不快,每次必须要重新哈希并做一次查找for k in d:print(k, '--->', d[k])# 更好的方法for k, v in d.items():print(k, '-->', d[k])if __name__ == '__main__':high_fun()

 

协助本站SEO优化一下,谢谢!
关键词不能为空
同类推荐
«    2025年12月    »
1234567
891011121314
15161718192021
22232425262728
293031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
文章归档
网站收藏
友情链接