functions&methods
(1)round(a,b)
a:输入的数字
b:保留的小数位数,不写默认取整
(2)sorted(iterable,key,reverse)
iterable:表示可以迭代的对象,
key:函数,用来选取参与比较的元素
reverse:指定排序顺序,reverse=True倒序,reverse=False时顺序,=false
(3)面向对象的方法
设置一个数组fam ,fam是一个对象,属于list型,method是与类或类的对象相关的函数,是一种特殊的function(函数),它必须和类相关
- family.function()这种调用有的时候会改变对象本身5/6/7,有的时候不会
(4)str.count(sub,start=,end=)计数
(5)str.upper() 小写字母变大写,对str类变量来说 不会改变其本身
(6)str.index(str, beg=0, end=len(string)) 检索是否存在子字符串并返回出现的次数
(7)s.append(x) 把x接到s尾后
(8)s.remove(x) 移除s中和x相等的第一项
(9)s.reverse() 把s倒排
import packages
A
#Import the math package
import math
math.floor()
#Calculate C
C = 0
C=2*math.pi*r
B
或若想使用特定功能(如math里的pi)
from math import pi
这样再调用就不需要敲math辽
C
再或者简单一点把math这种package缩写 利用as
from scipy.linalg import inv as my_inv
my_inv([[1,2], [3,4]])
Numpy
在list的基础上,引入array,使得list的计算更方便,但也带来了不同,且会改写数组中数据的类型,强制类型转换
a=[1,2,3] b=[1,2,3]
c = a+b #=[1,2,3,1,2,3]
import numpy as np
np.a=[1,2,3] np.b=[1,2,3]
c=np.a+np. b #=[2,4,6]
np.array强制把输入的数据都转换成了同一个类型
In [1]:
... np.array([True, 1, 2, 3, 4, False])
Out[1]: array([1, 1, 2, 3, 4, 0])
In [2]: np.array([4, 3, 0]) + np.array([0, 2, 2])
Out[2]: array([4, 5, 2])
In [3]: np.array([1, 1, 2]) + np.array([3, 4, -1])
Out[3]: array([4, 5, 1])
In [4]: np.array([0, 1, 2, 3, 4, 5])
Out[4]: array([0, 1, 2, 3, 4, 5])
eg:利用np.array做筛选
# height and weight are available as a regular lists
# Import numpy
import numpy as np
# Calculate the BMI: bmi
np_height_m = np.array(height_in) * 0.0254
np_weight_kg = np.array(weight_lb) * 0.453592
bmi = np_weight_kg / np_height_m ** 2
# Create the light array
light=bmi<21
# Print out light
print(light)
# Print out BMIs of all baseball players whose BMI is below 21
y=np.array(bmi)
print(y[light])
二维数组
In [10]: np_2d[0]
Out[10]: array([ 1.73, 1.68, 1.71, 1.89, 1.79])
In [11]: np_2d[0][2]
Out[11]: 1.71
In [12]: np_2d[0,2] #与np_2d[0][2]指代同一个元素,[行,列]
Out[12]: 1.71
In [13]: np_2d[:,1:3] #注意这种方[a:b,c:d] :a-b行,c-d列
Out[13]:
array([[ 1.68, 1.71],
[ 59.2 , 63.6 ]])
2D Numpy arrays
conversion = np.array([0.0254,0.453592,1])
Basic Statistic
np.mean np.median
np.corrcoeff相关度
np.corrcoef(np_baseball[:,0],np_baseball[:,1])
np.std 标准差standard deviation .
np.round(np.random.norma(60.32,15),2))
(60.32均值, 15标准差, 5000样本容量, 输出的shape默认是none只输出一个只),2保留的小数位数)标准正态分布