Python 學習小結
1 使用idel新建立程序后,保存運行,CTRL+F5即可運行
2 if (time==12):
print 'hello'
else:
pring 'dsdsd'
//注意冒號!
3 包、模塊的命名規則:全部以小寫字母形式命名
4 類名首字母大寫,其他字母小寫;私有屬性和私有方法用兩個下劃線做前綴,SELF=JAVA中的this
5 函數命名規則:函數名必須下劃線或者字母開頭,可以包含任意的數字,字母和下劃線組合,函數名
區分大小寫,函數名不能保留字
6 注釋用 #號,中文注釋 #* coding:UTF-8 *
7 PYTHON不強制使用分號
8 PYTHON類型
1) 整型
分別為布爾型(0:FALSE,1:TRUE),長整型和標準整數類型;長整型相當于JAVA.BIGINTEGER,在后
面加L表示
2)雙精度類型,E記數,相當于c的double
3)復數,比如0+2j,其中num.real,num.imag分別返回其實部和虛部,num.conjugate(),返回其共扼復數對象
9 PYTHON不支持i++,i--的運算
10 全局變量,使用global 關鍵字
11 字符串知識
1)‘hello' --//輸出'hello' 原樣輸出hello
2) "hello" //輸出"hello"
3) "what 's your name" 輸出"what's your name
4)三引號:其中的字符串可以任意使用單引號和雙引號
>>> '''what's your name,'this is a pig' '''
輸出:"what's your name,'this is a pig' "
5)也可以轉義,比如
>>>'what \'s your name'
6) 字符串連接用+號
7)print str('hello') //輸出hello,將其轉為字符串的形式
8)字符串的輸入函數 input(),把輸入數據改為默認的python表達
式,而raw_input()是將讀入的數據轉換為字符串
比如raw_input('我的年齡')
12 整除
3/6=0,這時因為兩個整數除的時候,python 2.5會對結果進行截取,只保留
整數部分。
3.0/6.0=0.5 ,如果參與除法個數中有一個是浮點數字,則是真正除(5。0/6)
from future import division
真除法:5/6=0.83333
而//叫地板除 用于兩個數的整除,比如5//6=0
乘方運算
33=27
13 falas,none,0,空字符串,空元素,空列表及空字典都是假(0),而其他值都是真值‘
14 if語句
if xxxx:
print ''
elif xxxx:
print 'xxxx'
elif xxx:
print 'xxxx'
注意是elif
15 while語句
while i<=5:
.......
else:
...........
16 for循環
for target in object:
....
if xxxx:
break
if xxxxx:
continue
else:
.......
17 迭代器
mab=['a','b','c','d']
my=iter(mab)
print my.next()
print my.next()
并行迭代:
names=[a','b','c','d']
ages=[2,4,5,7]
for name,age in zip(names,ages) :
print name,'的年齡是',age
zifu=raw_input('輸入您要查詢鮮花的名稱:')
shujus=['長春花','珍珠花','向日葵','風鈴草','金盞菊','含羞草','夾竹桃','大麗花','金雀花','野薔薇','桔梗花']
for index,shuju in enumerate(shujus):
if zifu in shuju:
print shuju
//其中enumerate為迭代器
18 while True:
word=raw_input('input name')
if not word:
break
..........
19 PASS語句
什么也不做
20 DEL語句
刪除名稱本身
name='abc'
del name
print name
動態執行python代碼
exec "print 'hello'"
21 PYTHON程序結構
由包,模塊和函數組成
22
# 函數的定義
def login (username = "maxianglin" , password = "maxianglin"):
if(username == 'admin') and (password == 'admin'):
print "登錄成功!"
else:
print "登錄失敗"
login('admin','admin')
login('admin')
login(password='admin')
login()
23 注意PYTHON 2下,WINDOWS下的話,里面有中文的話,將其保存為GBK編碼再運行,PYTHON3則沒這個問題。
24 函數中的可變長度參數值
比如def login ( userpwds):
username=userpwds[0];
...................
調用login('a','b')
25 方法需要返回值的話,則只需要return 即可
26 方法需要返回多個值,可以使用元組的方法
比如def abc(x,y,z)
x=x+5
y=y+4
z=z+6
opera=[x,y,z]
numbers=tuple(opera)
return numbers
27 模塊的創建
abc.py
def test():
.......
調用方:
import abc
ab.test();
//或者from abc import test
from abc import //導入所有模塊
python的import可以放在任何位置
28 # -- coding: UTF-8 --
import sys
print updatePwd.updatePassword().decode('UTF-8').encode(type)
用這里調用結果用decode轉換為UTF-8了
29 模塊中的屬性
1) name屬性 :用來判斷當前模塊是不是程序的入口,如果是入口,則返回main
2) DOC:每個對象都會有doc,用來描述注釋作用,比如
class myclass:
'adsdfsdfsdf'
...............
print myclass.doc //輸出adsdfsdfsdf
30) 內設的模塊函數
1、apply()函數
def login (username , password):
msg = ''
if(username == 'admin') and (password == 'admin'):
msg = '登錄成功'
else:
msg = '登錄失敗'
return msg
print apply(login,('admin','admin'))
把函數的參數存放在一個元組或序列中
2 filter()函數
用函數來過濾序列,把序列的每一個項傳遞到過濾函數中去,如果函數返回TRUE則過濾,并一次性返回
其結果,如果過濾函數返回的結果為FALSE,則從列表中刪除該項目。
def validate (usernames):
if (len(usernames) > 4) and (len(usernames) < 12):
return usernames
print filter(validate , ('admin','maxianglin','mxl','adm','wanglili'))
將('admin','maxianglin','mxl','adm','wanglili')傳進去進行過濾
3 reduce函數
def operat (x , y):
return x*y
print reduce(operat , (1,2,3,4,5,6))
print reduce(operat , (7,8,9) , 5)
其中,對(1,2,3,4,5,6)進行每一個的連乘;
4 map函數
對多個序列中的每個元素執行相同的操作,并返回一個與輸入序列長度相同的列表。
def add1(a):
return a + 1
def add2(a, b):
return a + b
def add3(a, b, c):
return a + b + c
a1 = [1,2,3,4,5]
a2 = [1,2,3,4,5]
a3 = [1,2,3,4,5]
b = map(add1, a1)
print b
b = map(add2, a1, a2)
print b
b = map(add3, a1, a2, a3)
print b
分別輸出:[2, 3, 4, 5, 6]
[2, 4, 6, 8, 10]
[3, 6, 9, 12, 15]
31 LIST
1) userList = ['0001' , '0002' , '0003' , '0004' , '0005']
print '目前有學生'+str(len(userList))+'個'
print '剛來一個學生'
userList.append('0006')
print '現有學生'+str(len(userList))+'個,他們是:'
for item in userList:
print item
2) insert方法
userList = ['0001' , '0002' , '0006' , '0004' , '0005']
print '初始化的userList列表為:'+str(userList)
userList[2] = '0003'
print '更新后的userList列表為:'+str(userList)
//注意序列從0開始算
3) 刪除元素remove
userList = ['0001' , '0002' , '0003' , '0004' , '0005']
print '初始化的userList列表為:'+str(userList)
userList.remove('0003')
4)del
del userlist[1]
5) 分片賦值
userList = list('Python')
userList[1:] = list('rite')
print userList
這里用冒號分片,從第3個元素開始到結束,改為rity,輸出pyrite
6)使用負索引訪問列表元素
userList = ['0001' , '0002' , '0003' , '0004' , '0005' , '0006']
print userList[-2]
最尾部元素為-1,-2即輸出005
7) 列表分片
userList = ['0001' , '0002' , '0003' , '0004' , '0005' , '0006']
subUser1= userList[2:5] //輸出索引2,3,4號位的元素,不包括索引為5的元素
subUser2= userList[-3:-1]
subUser3= userList[0:-2] //輸入不0開始,不包括-2元素位(即0005)的所有元素
print subUser1
print subUser2
print subUser3
['0003', '0004', '0005']
['0004', '0005']
['0001', '0002', '0003', '0004']
8) 二元表
有點象數組:
userList1=['0001' , '0002' , '0003' , '0004']
userList2=['0005' , '0006' , '0007']
userList=[userList1 , userList2]
則userList[0][1]=0002
列表可以連接:
userList1=['0001' , '0002' , '0003' , '0004']
userList2=['0005' , '0006' , '0007']
userList1.extend(userList2)
print userList1
將userLIst2加到userList1后去
userList6= ['0015' , '0016']*2 //將其中的元素添加一杯 ['0015','0016','0015','0016']
9 ) 列表的查找,排序和反轉
查找:userList = ['0001' , '0002' , '0003' , '0004' , '0005' , '0006']
print '元素0002對應的索引值為:',userList.index('0002')
排序:userList = ['0001' , '0004' , '0006' , '0002' , '0005' , '0003']
userList.sort(reverse=True)
print userList
//默認是升序,如果設置參數reverse=true,則為降序
反轉:userList = ['0001' , '0004' , '0006' , '0002' , '0005' , '0003']
userList.reverse()
32 POP操作:userlist.pop() //彈出
append:入棧操作
33 不可變序列:元組
1) 創建元組,創建時可以不指定元素的個數,相當于不定長的數組,但一旦創建就不能修改元組的長度。
如果只有一個數的元組,則必須指定為比如(42,),注意后面加上一個逗號
元組: user=('1','2','3','4','5') ,元組的長度不可變,同樣索引從0開始
2) 添加元組
userTuple = ('0001' , '0002' , '0003' , '0004' , '0005' , '0006')
new_userTupele=(userTuple , '0007' , '0008')
3 )元組中的元素不能修改
4) 同樣支持分片
userTuple = ('0001' , '0002' , '0003' , '0004' , '0005' , '0006')
print '元組中的第3個元素為:',userTuple[2]
print '元組中倒數第3個元素為:',userTuple[-3]
print '元組中第3個元素到倒數第2個元素組成的元組為:',userTuple[2:-1]
5) 元組可以進行解包操作
userTuple = ('0001' , '0002' , '0003')
stu1 , stu2 , stu3 = userTuple
print stu1
print stu2
print stu3
6)元組的遍歷
for range的用法
userTuple = ('0001' , '0002' , '0003' , '0004' , '0005' , '0006')
for item in range(len(userTuple)):
print userTuple[item]
還可以用MAP
userTuple1 = ('0001' , '0002' , '0003')
userTuple2 = ('0004' , '0005' , '0006')
userTuple=(userTuple1 , userTuple2)
for item in map(None , userTuple):
for i in item:
print i
MAP中的NONE時,則MAP返回其后面的元組
34 字典
userDic = [(2,'maxianglin'),(1,'wanglili'),(3,'malinlin')]
dic_userDic = dict(userDic)
print dic_userDic
輸出為:{1:'wanglili',2:'maxlinlin',3:'malinlin'}
或者usera={'0000':'sssss','ssss':'tom'}
操作:
1) 字典添加元素
字典是無序的,沒append方法,向其調用增加一個元素,用setdeffault()方法
userDic={'0001':'maxianglin','0002':'wanglili','0003':'malinlin'}
userDic.setdefault('0004','zhuhongtao')
print userDic
userDic.setdefault('0001','zhangfang') //重復元素,添加失敗,依然是原來的
print userDic
也可以直接改值 userDic['0004']='ddddd'
刪除值:
del(userdic['0002']);
也可以 userdic.pop
2) 字典的遍歷
for in遍歷
userDic={'0001':'maxianglin','0002':'wanglili','0003':'malinlin'}
for key in userDic:
#print 'userDic[%s]='% key,userDic[key]
print userDic.items()
還有用items方法遍歷字典,比如
userDic={'0001':'maxianglin','0002':'wanglili','0003':'malinlin'}
for (key,value) in userDic.iteritems():
print 'userDic[%s]='% key,value
還有iterkeys()和itervalues,
for key in userDic.iterkeys():
print key
for value in userDic.itervalues():
print value
for (key ,value) in zip(userDic.iterkeys(),userDic.itervalues()):
print 'userDic[%s]='% key,value
3) 字典的基礎方法
clear():清除字典里的所有項 userDic.clear()
copy()方法:userDic.copy()
fromkeys()方法:
source_userDic= {'0001':'maxianglin','0002':'wanglili','0003':'malinlin'}
print {}.fromkeys(['0001','0002'])
print source_userDic.fromkeys(['0001','0002'])
print source_userDic.fromkeys(['0001','0002'],'maxianglin')
其中fromkeys中第一個參數是新的字典的列表,第2個參數是值
{'0001': None, '0002': None}
{'0001': None, '0002': None}
{'0001': 'maxianglin', '0002': 'maxianglin'}
4) 字典的get方法
userDic= {'0001':'maxianglin','0002':'wanglili','0003':'malinlin'}
print userDic.get('0002')
//當get訪問不存在的值的時候,返回的是NONE,不會有異常
5) has_key()方法
找字典中是否有該鍵,如果有返回true.
userDic.has_key('abc')
6)popitem()方法
彈出棧,userDic.popitem()
7) update方法,用一個字典更新另外一個字典
userDic= {'0001':'maxianglin','0002':'wanglili','0003':'malinlin'}
newDic={'0002':'zhangfang'}
userDic.update(newDic)
print userDic
則更新0002的值
35 序列
numbers=[0,1,2,3,4,5,6,7,8,9]
numbers[3:6] ,表示從第3個元素開始,但不包括第6個元素的值,輸出3,4,5
numbers[7:] 則取到最后,從第7個開始,即7,8,9
更大的步長
又如numbers[0:10:1] ,指定了步長為1,默認為1,輸出[0,1,2,3,4,5,6,7,8,9]
如果設置步長為2,則跳過元素
[0,2,4,6,8]
還可以number[::3],只有步長,輸出[0,3,6,9]
轉自:http://jackyrong.iteye.com/blog/1404268