Python Primer Base Code

Source: Internet
Author: User

#查找index函数的帮助
Help (Str.index)
#for循环和break语句
From math import sqrt
For I in Range (2,101):
Flag=1
K=int (sqrt (i))
For j in Range (2,k+1):
If i%j==0:
Flag=0
Break
if (flag):
Print I
#continue语句, the statement that satisfies the condition to jump out of continue
Suma=0
I=1
While i<=5:
Suma+=i
I+=1
If i==3:
Continue
print ' i=%d,sum=%d '% (I,suma)
#循环中的else语句
K=5
For I in Range (1,10):
If k==3:
Break
Else
Print I
#自定义函数/footage 1-100 Prime
From math import sqrt
def isprime (x):
If x==1:
Return False
K=int (sqrt (x))
For j in Range (2,k+1):
If x%j==0:
Return False
Return True
For I in Range (2,101):
If IsPrime (i):
Print I

def f (x,y=true): #默认参数要放在参数列表的最后
' x and Y both correct words or not '
If y:
Print x, ' and y both correct '
Print x, ' is Ok '
F (68)
F (68,false)
#传递函数
def addme2me (x):
Return (X+X)
def self (f,y):
Print f (Y)
Self (addme2me,2.2)
#lambda函数
My_add=lambda X,y:x+y
My_add (5,6)

#数据获取与表示
F=open (R ' E:\360Downloads\firstpro.txt ', ' W ') #新建一个文件
F.write (' Hello,world ') #f为对象, write writes to file
F.close ()

F=open (R ' E:\360Downloads\firstpro.txt ', ' R ') #r代表读出
P1=f.read (5) #5代表读出的字节数
P2=f.read ()
Print P1,P2
F.close

F1=open (R ' E:\360Downloads\companies.txt ')
Cname=f1.readlines ()
For I in range (0,len (CNAME)):
Cname[i]=str (i+1) + "+cname[i"
F1.close
F2=open (R ' E:\360Downloads\scompanies.txt ', ' W ')
F2.writelines (CNAME)
F2.close ()

#网络数据获取
Import Urllib
R=urllib.urlopen (' http://z.cn/')
Html=r.read

#序列
#标准类型运算符
' Apple ' < ' banana '
[1,2,3]!=[4,5,6] #值比较
atuple= (' Ba ', 126.4)
Btuple=atuple
Btuple is not atuple# object identity comparison
(' 86.40 ' < ' 122.64 ') and (' Apple ' < ' banana ') #布尔运算
#序列类型运算符
week=[' Mondy ', ' Tuesday ', ' Wednesday ', ' Thursday ', ' firday ', ' satuday ', ' Sunday '
Print week[1],week[-2], ' \ n ', week[1:4], ' \ n ', week[:6], ' \ n ', week[::-1] #序列值的序号是从0开始到N-1 or from 1 to n
' Apple '
' Ba ' in (' Ba ', ' the Boeingcompany ')
#序列类型转换工厂函数
List (' Hello,world ') #将字符串转成列表
Tuple (' Hello,world ') #将字符串转成元组

#字符串
s1= "' Hello
A
' B '
world! ""
S1 #三引号可以保持里面字符串的原貌

S2=r ' d:\python\a.py '
S2

ccode=[' AXP ', ' ba ', ' cat ', ' csco ', ' CVX ']
cprice=[' 86.40 ', ' 122.64 ', ' 99.44 ', ' 23.78 ', ' 115.91 ']
For I in range (5):
print '%d%8s:%8s '% (I,ccode[i],cprice[i]) #%8s refers to 8 characters
print ' I get%d%%! '%32 #两个 percent will leave a

Astr= ' What does your think of this saying "no pain,no gain"? '
Tempstr=astr.split (' \ "') [1] #\" is an escape character
If Tempstr.istitle ():
print ' It is title format '
Else
print ' It is not title format '
Print Tempstr.title ()

Astr= ' \101\t\x41\n ' #\ octal number 000 represents the character \ t represents a horizontal tab
Print Astr

#列表
JSCORES=[9,9,8.5,10,7,8,8,9,8,10]
Ascore=9
Jscores.sort ()
Jscores.pop () #去掉最高分
Jscores.pop (0) #去掉最低分
Jscores.append (Ascore) #合并
Avescore=sum (jscores)/len (jscores)
Print Avescore

week=[' Monday ', ' Tuesday ', ' Wednesday ', ' Thursday ', ' Firday ']
weekend=[' Saturday ', ' Sunday ']
Week.extend (Weekend) #extend合并函数
For I,J in Enumerate (week): #enumerate函数 produces a sequence starting from 0
Print I+1,j

numlist=[3,11,5,8,16,1]
Numlist.sort (reverse=true) #按逆序排列
Numlist
fruitlist=[' apple ', ' banana ', ' pear ', ' lemon ', ' avocado '
Fruitlist.sort (Key=len)
Fruitlist #按字符长度排序
#列表解析
[X**2 for X in range (10)]
[X**2 for X in range (ten) if X**2&LT;50]
[(x+1,y+1) for x in range (2) for Y in range (2)]

#元组
Atruple= (a)
Atruple
Atruple[1:]
Len (atruple)
btruple= ([' Monday ', 1],2,3)
BTRUPLE[0][1]
, #创建元组2014
alist=[' AXP ', ' ba ', ' Cat ']
atruple= (' AXP ', ' ba ', ' cat ')
Alist[1]= ' Alibaba '
Atruple[1]= ' Alibaba ' #元组是不可变的, the list is mutable
alist=[3,5,2,4]
Alist.sort () #改变原来列表
Alist
alist=[3,5,2,4]
Sorted (alist) #sorted只是新生成一个列表的副本, the original list has not changed
Alist
#但元组就只能使用sorted, cannot use sort, because tuples cannot be changed
Atruple= (3,5,2,4)
Atruple.sort #会报错

def func (args1,args2= ' World '): #元组作为函数形式的参数
Print ARGS1,ARGS2
Func (' Hello ',)
Func (args2= ' Apple ', args1= ' hello ')
def func (Args1,*args):
Print ARGS1
Print args
Func (' Hello, ', ' Wangdachui ', ' Liuyuan ', ' Linlin ')
#返回值类型为元组的函数enumerate (), coerce ()

#字典
ainfo={' Wangdachui ':, ' Niuyun ': +, ' linlin ': ' #直接创建字典
info=[(' Wangdachui ', +), (' Niuyun ', +), (' Linlin ', 3000)]
Binfo=dict (Info) #利用dict函数创建字典
Cinfo=dict ([[' Wangdachui ', 3000],[' Niuyun ', 2000],[' Linlin ', 3000]])
Dinfo=dict (wangdachui=3000,niuyun=2000,linlin=3000)

Adict={}.fromkeys (' Wangdachui ', ' Niuyun ', ' Linlin '), #fromkeys函数将所有的keys初始值设置为3000
Adict

plist=[(' AXP ', ' American Express ', ' 86.40 '), (' Ba ', ' the ' Boeing Company ', ' 122.64 '), (' Cat ', ' Caterpillar Inc. ', ' 99.44 ')]
Alist[]
Blist[]
For I in range (2):
ASTR=PLIST[I][0]
BSTR=PLIST[I][2]
Alist.append (ASTR)
Blist.append (BSTR)
Adict=dict (Zip (alist,blist)) #zip函数
#字典的使用
#字典的基本操作
ainfo={' Wangdachui ':, ' Niuyun ': +, ' Linglin ': 4500, ' Tianqi ': 8000}
ainfo[' Niuyun '] #键值查找
ainfo[' Niuyun ']=9999# update
Ainfo
ainfo[' Funyun ']=1000# find
' Mayun ' in Ainfo #成员判断
Del Ainfo #删除字典

ainfo={' Wangdachui ':, ' Niuyun ': +, ' Linglin ': 4500, ' Tianqi ': 8000}
For key in Ainfo.keys ():
print ' name=%s,salary=%s '% (Key,ainfo[key])
"Niuyun ' s salary is% (Niuyun) s."%ainfo #% (key) format specifier% Dictionary object name
ainfo={' Wangdachui ':, ' Niuyun ': +, ' Linglin ': 4500, ' Tianqi ': 8000}
Ainfo.keys ()
Ainfo.values ()

ainfo={' Wangdachui ':, ' Niuyun ': +, ' Linglin ': 4500, ' Tianqi ': 8000}
binfo={' Wangdachui ':, ' Niuyun ': 9999, ' Linglin ': 4500, ' Wangzi ': 8000}
Ainfo.update (binfo) #update函数 Quick Change
Ainfo

astock={' AXP ': 86.4, ' BA ': 122.64}
Bstock=astock
astock={} #此时只会讲astock清空, the bstock will not be emptied and the clear function will be used to delete the associated
Bstock
Astock.clear ()
Bstock
#字典作为函数的形式参数
def func (ARGS1,*ARGST,**ARGSD): #一个 * is a variable long positional parameter, * * variable long keyword parameter
Print ARGS1
Print Argst
Print ARGSD

Func (' Hello ', ' Wangdachui ', ' Niuyun ', ' Linglin ', a1=1,a2=2,a3=3)

#集合
names=[' Wangdachui ', ' Niuyun ', ' Wangzi ', ' Wangdachui ', ' lingling ', ' Niuyun ']
Namesset=set (names) #set删除重复对象 because the elements of the collection are not duplicated
Namesset
Aset=set (' Hello ')
Aset
Fset=frozenset (' Hello ')
Fset
#集合比较
Aset=set (' Sunrise ')
Bset=set (' Sunset ')
' U ' in Aset
Aset==bset
Set (' Sun ') <aset

Aset&bset #集合关系运算
Aset|bset
Aset-bset
Aset^bset #不能同时属于两个集合
Aset-=set (' Sun ') #运算符可复合
#集合内建函数
Aset=set (' Sunrise ')
Bset=set (' Sunset ')
Aset.issubset (bset) #是否为子集
Aset.intersection (bset) #交集
Aset.difference (bset) #差补
Cset=aset.copy () #拷贝
#面向可变集合的函数
Aset=set (' Sunrise ')
Aset.add ('! ')
Aset
Aset.update (' Yeah ')
Aset.remove ('! ')
Aset.clear ()
#扩展库scipy
Import NumPy as NP
Xarray=np.ones ((3,4)) #生产3 all 1 matrix
Xarry

From scipy import Linalg
Arr=np.array ([[1,2],[3,4]])
Linalg.det (arr)

#ndarry
From numpy Import *
Aarray=array ([i])
Aarray
Barray=array ([(+), (4,5,6)])
Barray
Zeros ((2,2))
Arange (1,5,0.5)

Aarray=array ([(+), (4,5,6)])
Sin (aarray)
Aarray.shape #数组的维度
Barray=aarray.reshape (3,2)
Barray
Aarray.sum ()
Aarray.sum (axis=0) #通过设置参数, row, column sum
Aarray.sum (Axis=1)
Carray=array ([1,3,5])
Carray[:1] #切片功能
Darray=array ([2,4,6])
Earray=array ([7,8,9])
where (Carray>2,darray,earray) #where函数

def fun (x, y):
Return (x+1) * (y+1)
Arr=fromfunction (fun, (9,9)) #fromfunction函数
Arr
#ufunc函数能对数组中每个元素进行操作, including functions such as add
Import NumPy as NP
A=np.arange (1,5)
B=np.arange (2,6)
Np.add (A, B)
Np.add.accumulate ([2,3,8])
Np.multiply.accumulate ([2,3,8])

#series
#series objects similar to one-dimensional arrays, consisting of data and indexes
from pandas import series
Import pandas as PD
ASER=PD. Series ([1,2.0, ' a '])
BSER=PD. Series ([' Apple ', ' peach ', ' lemon '],index=[1,2,3])
Bser.index
bser.values
aser[' a ']
import numpy as NP
Np.exp (aser)
#series数据对齐
data={' AXP ': ' ', ' csco ': ' 122 ', ' BA ': ' 94 '}
sindex=[' AXP ', ' Csco ', ' AAPL ']
ASER=PD. Series (data,index=sindex)
Aser
Pd.isnull (aser)
#series的name属性
aser.name= ' cnames '
Aser.index.name= ' volume '
aser

#dataframe表结构
#大致可以看成共享一个index的series的集合
data={' name ': [' Wangdachui ', ' Linlin ', ' Niuyun '], ' pay ': [4000,5000,6000]}
FRAME=PD. DataFrame (data)
frame[' name ']
Frame.pay
Frame.ix[2] #索引所对应的数据
#dataframe对象的修改和删除
frame[' name ']= ' Admin ' #对name下的所有元素进行更改
del frame[' pay ']
frame
frame.index.name= ' no '
#便捷数据获取
# Convenient network data yahoo Finance
from matplotlib.finance import Quotes_historical_yahoo
from datetime import Date
Import pandas as PD
Today=date.today ()
start= (today.year-1,today.month,today.day)
Quotes=quotes_historical_yahoo (' AXP ' , Start,today)
DF=PD. DataFrame (quotes)
Print df
#自然语言工具包NLTK
from Nltk.corpus Import Gutenberg
Import NLTK
Print Gutenberg.fileids ()

#数据准备
From matplotlib.finance import Quotes_historical_yahoo
From datetime import Date
Import Pandas as PD
Today=date.today ()
Start= (Today.year-1,today.month,today.day)
Quotes=quotes_historical_yahoo (' AXP ', start,today)
fields=[' Date ', ' open ', ' close ', ' High ', ' low ', ' volume '
QUOTESDF=PD. DataFrame (Quotes,columns=fields) #通过columns数据加属性名
QUOTESDF=PD. DataFrame (Quotes,index=range (1,len (quotes) +1,columns=fields)
Print QUOTESDF

From datetime import Date
From datetime import datetime
Y=datetime.strftime (x, '%y-%m-%d ') #将日期转换成固定格式
Import Pandas as PD
Dates=pd.date_range (' 20141001 ', periods=7) #自己创建时间序列
Dates
#数据显示
Djidf.index
Djidf.columns
Djidf.values
djidf.describe# Display Data Description
Djidf.head (5) #显示前五行数据
Djidf.tail (5)
#数据选择
Quotesdf[u ' 2013-12-02 ': U ' 2013-12-06 '] #dataframe可以使用索引选择
djidf[' Code ']
Djidf.loc[1:5,] #通过loc通过标签选择数据, the first parameter is the row label, the second argument is the column label
djidf.loc[:,[' code ', ' Lasttrade '] #前面这个: Required
djidf.loc[1:6,[0,2]] #通过的行位置, column position Selection tab
Quotesdf[quotesdf.index>=u ' 2014-01-01 ']
quotesdf[(quotesdf.index>=u ' 2014-01-01 ') & (quotesdf.close>=95)] #条件筛选
#简单统计预处理
Djidf.mean (columns= ' Lasttrade ') #最近一次成交价的平均值
djidf[djidf.lasttrade>=120].name# company name with the most recent transaction price greater than or equal to 120
Len (Quotesdf[quotesdf.close>quotesdf.open]) #股票涨的天数
Len (QUOTESDF)-131
Status=np.sign (Np.diff (quotesdf.close)) #np. diff The difference between two consecutive days of data
Status[np.where (status==1.)]. Size
Djidf.sort (columns= ' Lasttrade ') [27:].name# sort results list the top three company names, altogether is 30 records, so yes [27:]
t=quotesdf[(quotesdf.index>=u ' 2014-01-01 ') & (Quotesdf.index<=u ' 2014-02-01 ')]
Len (t) #统计2014年1月份的股票开盘天数

#分组
Tempdf.groupby (' month '). Count (). Month #每个月的股票开盘天数
Tempdf.groupby (' month '). SUM (). Volume #每个月的股票总成交量
G=tempdf.groupby (' month ')
gvolume=g[' volume ']
Print Gvolume.sum ()
#合并
#append追加 portrait
P=quotesdf[:2]
Q=quotesdf[u ' 2014-01-01 ': U ' 2014-01-05 '
P.append (q)
#concat连接
Pieces=[tempdf[:5],tempdf[len (Tempdf)-4:]]
Pd.concat (Pieces)
#两个不同逻辑结构的对象能否连接 portrait
Piece1=quotesdf[:3]
Piece2=tempdf[:3]
Pd.concat ([Piece1,piece2],ignore_index=true)
#join连接 Landscape
Pd.merge (djidf,akdf,on= ' code ')
Pd.merge. (djidf,akdf,on= ' Code '). Drop ([' Lasttrade '],axis=1)
#聚类分析
From Pylab Import *
From SCIPY.CLUSTER.VQ Import *
LIST1=[88,74,96,85]
LIST2=[92,99,95,94]
LIST3=[91,87,99,95]
LIST4=[78,99,97,81]
LIST5=[88,78,98,84]
LIST6=[100,95,100,92]
Data=vstack ((LIST1,LIST2,LIST3,LIST4,LIST5,LIST6))
Centroids,_=kmeans (data,2)
RESULT,_=VQ (Data,centroids)
Print result

Python Primer Base Code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.