【Python】Library

random

random库,用于生成伪随机数

QQ20200413-0

matplotlib

绘图/可视化(仿matlab)

1
2
3
4
5
6
7
8
import matplotlib as mpl
import matplotlib.pyplot as plt

x = [1,3,5,7]
y = [4,9,6,8]
plt.plot(x, y)
plt.show()
# 绘制以x为横坐标,y为纵坐标的折线图

绘制y=x^2和y=x的图形

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import matplotlib.pyplot as plt

plt.axis("scaled")
plt.xlim(0,1) # x显示的范围
plt.ylim(0,1) # y显示的范围
plt.grid(True)
X1 = []
Y1 = []
Y2 = []
x = 0

while x<=1:
X1.append(x)
Y1.append(x)
Y2.append(x * x)
plt.plot(X1, Y1)
# plt.plot(X1, Y1, color="red") 把线的颜色改成红色
plt.plot(X1, Y2)

plt.show()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
sinY = []
cosY = []
trigX = []
angle = -180
while angle <= 180:
x = math.pi / 180 * angle
trigX.append(x)
y = math.sin(x)
sinY.append(y)
y = math.cos(x)
cosY.append(y)
angle = angle + 10

plt.scatter(trigX, sinY) #散点图
plt.scatter(trigX, cosY)
plt.title("...") #标题
plt.legend(["sin(x)", "cos(x)"]) #图例
plt.grid(True) #网格线
plt.show()
1
2
3
4
5
6
7
8
t = np.arrange(-1, 3, .01) #间隔0.01
s = np.sin(2 * np.pi * t)
c = np.cos(2 * np.pi * t)
plt.plot(t, s)
plt.plot(t, c)

plt.axis([-1, 3, -1, 2])
....
1
plt.pause(0.1) # 动态绘制(停顿0.1s)

sys

提供python运行环境的变量和函数

image-20200601162002653

不使用input()向程序输入值:

1
2
3
4
5
>>> sys.argv[0] # 程序的文件名
>>> sys.argv[1] # 第一个参数
>>> sys.argv[2] # 第二个参数
...
>>> sys.argv[3] # 第n个参数
1
2
3
4
5
import sys
print(sys.argv[0])
print(sys.argv[1])
print(sys.argv[2])
print(int(sys.argv[1]) * int(sys.argv[2]))

标准输入输出:

sys.stdin

sys.stdout

1
2
3
s = sys.stdin.readlines() #标准输入,完成多行输入
sys.stdout.write("abc") #标准输出,和print的差别在于不会自己在末尾换行
#sys.stdout.write("abc"+"\n")等同于print("abc")