Python 学习小技巧

现在在上的课经常用到python,想要通过这个文章记录一些小技巧

1.编写API

# The API of the function:
#
#  name(x, h, noff_m, noff_h)
#     Returns the discrete, linear convolution of two sequences.
#
#     Parameters: 
#         x,h: array_like
#             The 2 input sequences.
#         noff_m, noff_h: int
#             n's offsets of the 2 input sequences.
#     Returns: (y, noff)
#         y: array_like
#             The output sequence.
#         noff: int
#             n's offset of the output sequence.

2.格式化输出

print('noff_%s =%2d, %s =' % (name, noff, name), seq)

3.lambda

例子:

seq_delta = lambda n_min, n_max: (np.array([ 1 if n==0 else 0 for n in range(n_min, n_max+1)]), 0 - n_min)
(n_min, n_max)=(0,49)
(x, noff_x) = seq_delta(n_min, n_max)

在这里,seq_delta就是一个函数,n_min, n_max就是变量,返回的是冒号后括号里两个参数,第一个是一个数组,第二个是一个数值

4.画图matplotlib.pyplot

import matplotlib.pyplot as plt    #使用matplotlib.pyplot数据库完成画图,并且在语言中用plt即可表述
# Un-comment the following line to use interactive matplotlib widget.
#%matplotlib widget

如果使用折线图,可以直接使用plot()和show()

plt.title("test") 
plt.xlabel("n")
plt.ylabel("x(n)")
n=[i for i in range(10)]
x=[i for i in np.arange(0,1,0.1)]
plt.plot(n, x) 
plt.show()

如果使用棉棒图,必须先声明fig, ax = plt.subplots()

fig, ax = plt.subplots()#将plt.subplots ()函数的返回值赋值给fig和ax两个变量。 plt.subplots ()是一个函数,返回一个包含figure和axes对象的元组
plt.title("test") 
plt.xlabel("n")
plt.ylabel("x(n)")
n=[i for i in range(10)]
x=[i for i in np.arange(0,1,0.1)]
plt.stem(n, x)#绘制序列图像

or

fig, ax = plt.subplots()#将plt.subplots ()函数的返回值赋值给fig和ax两个变量。 plt.subplots ()是一个函数,返回一个包含figure和axes对象的元组
ax.set_title("test") 
ax.set_xlabel("n")
ax.set_ylabel("x(n)")
n=[i for i in range(10)]
x=[i for i in np.arange(0,1,0.1)]
ax.stem(n, x)#绘制棉棒图

如果想使用点表示图形:

plt.title("test") 
plt.xlabel("n")
plt.ylabel("x(n)")
n=[i for i in range(10)]
x=[i for i in np.arange(0,1,0.1)]
plt.plot(n, x,"ob") 
plt.show()

 如果一幅图想画多个图像,可以如下:

#2行1列,下标从0开始
fig, axs = plt.subplots(2, 1, sharex=True, sharey=True)
n=[i for i in range(10)]
x=[i for i in np.arange(0,1,0.1)]
y=[i for i in np.arange(1,2,0.1)]
axs[0].stem(n, x)
axs[0].set_ylabel('x(n)')
axs[1].stem(n, y)
axs[1].set_ylabel('y(n)')
axs[1].set_xlabel('n')

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值