python常用用法
本文大部分内容归纳自b站up主@啥都会一点的研究生,视频bv号BV1nG411w7qw,侵联删
书写习惯和用法
1. 打印含有变量的语句
坏习惯
def case 1(name,score):
if score 60.0:
print("Congratulations name "your score is "str(score))
else:
print("Sorry name "you didn't pass the exam")
好习惯
def case_1(name,score):
if score 60.0:
print(f"Congratulations {name}!your score is {score}")
else:
print(f"Sorry {name},you didn't pass the exam")
2. 判断条件
在python当中使用if结合bool(x)和len(x)与直接写x效果相同,为了可读性建议写上len
None、False、0、空列表、空元祖、空集合、空字典等,都表示否定。
def case_3(x):
if x:
pass
if bool(x):
pass
if len(x):
pass
3. 文件读写
坏习惯
这里如果写入发生错误,则文件不会被关闭
def case 5(filepath):
f open(filepath,"w")
f.write("Hello world\n")#here
f.close()
好习惯
使用with,发生异常也能正确关闭
def case_5(filepath):
with open(filepath)as f:
f.write("Hello world\n")
4. 较多位数数字写法(下划线)
可以这样加下划线增加可读性
def case 6():
×=10_000_000
易混淆的运算符^和**
【x ^ y】x 按位异或 y
【x ** y】x 的 y 次幂
5. debug 程序的方式
坏习惯
用 print 来 debug 程序
def case_7():
print("debug info")
print("normal info")
print("error info")
好习惯
使用 logging 打印日志:(更清晰)
import logging
def case_8():
logging.debug("debug info")
logging.info("normal info")
logging.error("error info")
def main():
level = logging.DEBUG
fmt = "[%(level)s](asctime)s -%(message)s"
logging.basicConfig(level=level,format=fmt)
case_8()
6. 可变类型参数
坏习惯
参数的默认值是在定义函数时定义的,而不是运行时,下图中,每次调用都会共享同一个列表,因此每次调用都会从之前的结果开始添加数据:
def case_9(n,1st=[]):
1st.append(n)
return 1st
1st1=case_9(0)#[0]
1st2=case_9(1)#[0,1]
好习惯
优化后:(每次调用相互不影响)
def case_9(n,1st=None):
if lst is None:
1st=[]
1st.append(n)
return 1st
1st1=case_9(0)#[0]
1st2=case9(1)#[1]
扩展
关于可变类型,在给函数传列表、字典时,稍不注意就会改动原始数据:
def case_10(1st):
lst2 = lst
1st2.append(1)
init_list [0,1,2]
case_10(init_list)init_list [0,1,2,1]
优化做法:(拷贝,构造新对象)
def case _10(1st):
1st2 = 1st[:] #lst.copy(),这里是拷贝而不是引用
1st2.append(1)
init_list [0,1,2]
case_10(init_list)init_list [0,1,2]
7. 字典遍历与推导式
遍历字典时,默认遍历键,以下两种方式效果相同:
def case_11():
d={"a":1,"b":2,"c":3}
for key in d:
pass
for key in d.keys():
pass
推导式可适用于列表、元组、字典、集合:
def case_12():
data=[0,1,2,3]
d {i:i * i for i in data}
1 [ii for i in data]
s {ii for i in data}
t (ii for i in data)
8.借助元组解包
形如 x(如下图)的数据其实都是元组,还包括return 返回值等:
def case_13():
x 1,2 tuple
d1=x[0]
d2=x[1]
9. 统计程序运行时间
通常会借助 time 库:time.time() 等
import time
def case_14():
t1 time.time()
time.sleep(1)
t2 time.time()
print(t2 t1)
但是精度一般,time.perf_counter()
具有最高测量分辨率,统计结果更准确
import time
def case_14():
t1 time.perf_counter()
time.sleep(1)
t2 time.perf_counter()
print(t2 t1)
10. 检查类型的方式
使用 isinstance 代替 “==” 检查类型,可避免 namedtuple 这种子类带来的判断错误问题:
from collections import namedtuple
def case_15():
line namedtuple('line',['k','b'])
1=1ine(1,5)
if type(1)=tuple:
print("it's a tuple")
else:
print("it's not a tuple")
if isinstance(1,tuple):
print("it's a tuple")
else:
print("it's not a tuple")