循环操作
python中的while、for循环
while循环
condition = 1
while condition < 10:
condition = condition + 1
print(condition)
此时输出为 2 3 4 5 6 7 8 9 10
for循环
example_list = [1,2,3,4,5,555,333,2,4]
for i in range(2,10,2):
print(i)
print("inner of for")
print('outer of for')
输出为
2
inner of for
4
inner of for
6
inner of for
8
inner of for
outer of for
定义函数
def function(a,b=5):
print('this is a function')
c = a+b
print(c)
function(1)
其中b为默认参数,默认参数要写到参数最后,则输出为6
def report(name,*grades):
total_grade = 0
for grade in grades:
total_grade += grade
print(name,'tatol grade is:',total_grade)
report('Mike',90,60,89)
其中*grades可以表示为多个参数,输出结果为90、60、89的和
对于一些简单的函数,可以使用lambda行内函数表示如下:
f = lambda x: x + 2 #定义函数f(x)=x+2
全局变量与局部变量
APPLY = 100
a = None
def fun():
global a
a = 20
print(a)
fun()
print(a)
其中APPLY为全局变量,a一开始为全局变量,在定义的函数fun()将a global了,这样在函数中的a便成了全局变量,因此上面程序的输出为:None 20
数据结构
列表、元组
对于下述代码
a = [1,2,3]
b = []
for i in a:
b.append(i + 2)
print(b)
可简化为
a = [1,2,3]
b = [i+2 for i in a]
print(b)
字典
创建字典
d = {'today':20, 'tomorrow':30}
d['tomorrow']
dict([['today',20],['tomorrow',30]])
dict.fromkeys(['today','tomorrow'],20)
库
numpy
numpy提供了数组功能
import numpy as np
a = np.array([2,0,1,5])
print(a) #创建数组
print(a[:3]) #输出数组前三位
print(a.min()) #输出数组最小值
a.sort() #将a的元素从小到大排序,此操作直接修改a
b = np.array([[1,2,3],[4,5,6]]) #创建二维数组
print(b*b) #输出二维数组的平方阵
scipy
Scipy提供了矩阵,其功能包含最优化、线性代数、积分、插值、拟合、特殊函数、快速傅里叶变换、信号处理和图像处理、常微分方程求解等。
from scipy.optimize import fsolve #导入求解方程组的函数
def f(x):
x1 = x[0]
x2 = x[1]
return [2*x1 - x2**2 - 1, x1**2 - x2 - 2]
result = fsolve(f,[1,1]) #求解f(x,y)=[1,1]
print(result) #输出结果,为array([1.91963957, 1.68501606])
#数值积分
from scipy import integrate #导入积分函数
def g(x): #定义被积函数
return (1-x**2)**0.5
pi_2, err = integrate.quad(g,-1,1) #积分结果和误差
print(pi_2 * 2) #由微积分知识指导积分结果为圆周率pi的一半
Matplotlib
主要用于二维绘图,也可以进行简单的三维绘图
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,10,1000) #作图自变量
y = np.sin(x) + 1 #因变量
z = np.cos(x**2) + 1 #因变量
plt.figure(figsize=(8,4)) #设置图像大小
plt.plot(x,y,label = '$\sin x + 1$', color = 'red', linewidth = 2)#作图,设置标签、线条颜色和大小
plt.plot(x,z, 'b--', label = '$\cos x^2 +1$') #作图,设置标签、线条类型
plt.xlabel('Time(s)')
plt.ylabel('Volt')
plt.title('A Simple Example') #标题
plt.ylim(0, 2.2) #显示的y轴范围
plt.legend() #显示图例
plt.show() #显示作图结果
Pandas
Pandas是Python下最强大的数据分析和探索工具。支持类似于SQL的数据增、删、查、改,并且带有丰富的数据处理函数;支持时间序列分析功能;支持灵活处理缺失数据等。
s = pd.Series([1,2,3], index=['a', 'b', 'c'])
d = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a', 'b', 'c'])
d2 = pd.DataFrame(s)
d.head() #预览前5行
d.describe() #数据基本统计量
catering_sale = 'data.xlsx'
data = pd.read_excel(catering_sale, index_col=u'日期') #制定日期为索引列