函数 循环 时间 文件读写
def function(list):
import time
start=time.time()
n=len(list)-1
list_max=list[0];
for i in range(n):
if list_max<list[i]:
list_max=list[i]
time.sleep(1)
end=time.time()
#print(('Running time: %s Seconds'%(end-start))
file=open("example.txt","w")
file.write(str(list_max))
file.close
return list_max,start,end
s,start,end=function([2,6,7,4,9,5,1,0,3,8])
print(s)
print('Running time: %s Seconds'%(end-start))
Numpy
矩阵定义&查看
import numpy as np
a=np.array([[1,2],[3,4]])
a.size
a.shape
a.ndim
向量矩阵生成
np.arange(10)
np.linspace(0,10,20)
np.zeros((5,5))
np.ones((3,3))
#随机数0-1
np.random.rand(5,5)
#随机高斯分布0-1
np.random.randn(5,5)
矩阵运算/拼接/形变
np.dot(a,b)
a.T
np.vstack([a,b])#竖直拼接
np.hstack([a,b])#水平拼接
np.concatenate((a,b),axis=0)#0垂直方向拼接 1水平方向拼接
np.reshape(m,(2,2))#前后维度成比例
Pandas
# In[]
import pandas as pd
# In[]
data=pd.DataFrame([1,2,3,4],columns=["umber"],index=["a","b","c","d"])
数据导入和存储
data=pd.read_csv("data.csv")
data.to_csv("data.csv")
数据连接&数据清洗
pd.concat([data1,data2])
data.append([data1,data2])
data.isnull()#判断位置是否为null
data.dropna()#null行删除
data.fillna(0)#把null用0填充
Matplotlib
# In[]
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0,10,1000)
y=np.sin(x)
plt.plot(x,y)
plt.legend()
plt.xlabel("x")
plt.ylabel("y")
#plt.xlim(0,5)
#plt.ylim(0,2)
plt.title("asdf")
plt.grid(True)
plt.show()
# In[]
y1=np.cos(x)
y2=np.exp(x)
plt.figure()
plt.subplot(2,1,1)
plt.plot(x,y1,"y-")
plt.subplot(2,1,2)
plt.plot(x,y2,"b--")
m=np.zeros([100,100,3])
m[10:20,:,:]=255
plt.imshow(m)
爬虫
# In[]
import requests
data=requests.get("https://www.csdn.net")
data.encoding="utf-8"#中文显示
print(data.status_code)#200表示成功
# In[]
#prox={"http":"http://1.1.10.102:88"}#代理列表反爬proxies=prox
header={'user-agent':'Mozilla/5.0'}#反爬
url="https://so.csdn.net/so/search/s.do?q=%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD&t=&u="
data=requests.get(url=url,headers=header)
html=data.text
# In[]
from bs4 import BeautifulSoup
soup=BeautifulSoup(html,"lxml")
lis=soup.find_all(name="dl",attrs={"class":"search-list J_search"})
for li in lis:
temp=li.find(name="div",attrs={"class":"limit_width"})
#temp=temp.find(name="a")
print(temp.text)
Requests&BeautifulSoup