1 Star 0 Fork 1

raulang/PythonProject-PythonLession

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
high_function2.py 2.21 KB
一键复制 编辑 原始数据 按行查看 历史
Gavan 提交于 2019-11-12 17:52 +08:00 . 1
''''''''''''''''''''''''''''''''''''''''
# 作者:cacho_37967865
# 博客:https://blog.csdn.net/sinat_37967865
# 文件:high_function2.py
# 日期:2019-09-09
# 主题:提升Python程序性能的好习惯2
'''''''''''''''''''''''''''''''''''''''''
import threading
def 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 += ', ' + name
print(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和value
d = {'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()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/raulang/PythonLession.git
git@gitee.com:raulang/PythonLession.git
raulang
PythonLession
PythonProject-PythonLession
master

搜索帮助