python(1):数据类型/string/list/dict/set等
本系列文章中, python用的idle是spyder或者pycharm, 兩者都很好用, spyder 是在anaconda 中的, 自帶了很多包可以用,
pycharm 只是個(gè)編譯器, 沒(méi)有很多包, 但是可以從anaconda 中傳過(guò)來(lái), 具體操作可以見(jiàn)我的另一篇博文.
Python2 與python3 語(yǔ)法略有差別.??本系列文章全部針對(duì) python3 以上版本!
spyder 中的快捷鍵: ctrl+1 注釋 , F5 運(yùn)行,? 上下鍵調(diào)用, #注釋,??\表示續(xù)行
''' abdfa''' 三引號(hào)可以實(shí)現(xiàn)換行
一行寫多條語(yǔ)句, 需要用分號(hào);
pycharm中的快捷鍵:??Ctrl + /? ?行注釋/取消行注釋,?
ctrl+D 復(fù)制本行到下一行(nice),??ctrl+y 刪除本行 ,?Shift + F10??? 運(yùn)行,?Shift + F9?? 調(diào)試??,ctrl+r 替換? ctrl+f 查找
如果運(yùn)行的按鈕是灰色的, 需要在倒三角的下拉菜單中
地方選擇一下?
左上角的下拉三角這邊 選擇 python ,同時(shí)在script path中找到文件的路徑, 之后就可以了.
?(一) python 基礎(chǔ)知識(shí)?
python的代碼極為精簡(jiǎn), 沒(méi)有分號(hào), if,for不用對(duì)應(yīng)寫end, 縮進(jìn)是 代碼的靈魂
區(qū)分大小寫? fish 與Fish不同的
v='28C'? 字符串可以單引號(hào)也可雙引號(hào) , v[-1]='C' ;??v[0:2] 表示0,1, 取不到2
長(zhǎng)度為n的序列索引: 0,1,2,3..n-1, 倒過(guò)來(lái)為-1,-2,...-n
v[0:-1] 獲取除去最后一個(gè)字符串以外的部分;??v[::-1] 倒序
float(v[0:-1]) 將字符串轉(zhuǎn)化為小數(shù)
格式化輸出:? print(' the price is: %.2f yuan'%x)? %.2f表示小數(shù)點(diǎn)有兩位
range(10) 表示 0-9 , 取不到10
簡(jiǎn)單輸入輸出:? ?price=input('please input a number:')
注: input()返回的類型是字符型str, 需要用int(), float()得到數(shù)值 , 可以用eval()將input當(dāng)做表達(dá)式來(lái)處理.
關(guān)鍵字: false, none, true, and as, break...
表達(dá)式: **乘方, //整除(得到商), % 取余, ~ , & , | ,? <=, >=, !=,==, not, and, or
增量賦值:? m%=5 表示 m=m%5,?a=a+3等價(jià)于a+=3? , 還有m**=2, a/=8??
鏈?zhǔn)劫x值: m=n=3.14, 先把3.14賦值給n, 再把n 賦值給m,?
多重賦值: x=1, y=2,可以輸出x,y=(1,2) , x,y=y,x 則馬上交換了順序, 不需要通過(guò)第三個(gè)變量,? ?其中逗號(hào), 表示元組
可以多個(gè)一起賦值:? x,y=1,2 兩個(gè)同時(shí)賦值
3<4<7 表示 (3<4) and (4<7)?
f=open(r'c:\python\test.py','w'); 或者f=open('c:\\python\\test.py','w');?
錯(cuò)誤 f=open('c:\python\test.py','w');?
python 自己的內(nèi)建函數(shù): abs(), bool(), round()四舍五入, int(), divmod(), pow(), float(), chr(), complex(),?dir(), input(), help(),?
輸入dir(__builtins__) 得到所有內(nèi)建函數(shù)名,??help(zip) 查看zip 函數(shù)的使用指導(dǎo).?
(二)六種數(shù)據(jù)類型
(1) 數(shù)值型(int , float , complex復(fù)數(shù))
int(4.5)=4,? 不可以int('你好')?
float(4)=4.0
9.8e3 代表9800.0,??-4.78e-2
complex(4)=4+0j
x=2.1+5.6j,??x.imag 虛部 , x.real? 實(shí)部, x.conjugate() 獲得共軛
str(123)
x//y商? x%y 余數(shù)? divmod(x,y)=(x//y,? x%y)
-10//3=-4, 保證余數(shù)是正的,? ?abs(x)
(2) string? 字符串, 可以用單引號(hào), 雙引號(hào), 三引號(hào)
print('\'nihao\'') #'nihao' print('\"nihao\"') #"nihao"\轉(zhuǎn)義符,?
其他也可以用轉(zhuǎn)義字符表示
a='\101\t\x41\n' b='\141\t\x61\n' print(a,b) #A A # a a字符串的索引: 從0 開(kāi)始計(jì)數(shù)?
注意, s='abc', 直接在console中輸入s 得到 'abc', 但是寫print(s) 則為 abc
s="I'm a student" s Out[2]: "I'm a student" type(s) Out[3]: str s='abc' s Out[5]: 'abc' s='''hello # 三引號(hào)可以讓字符串保持原貌 word''' s Out[7]: 'hello\nword's=r'd:\python\test.py' # 原始字符串 s Out[9]: 'd:\\python\\test.py'實(shí)例
a='hello' #也可以 a=''hello'', a='''hello''' print(a[2]) #l print(a[0:2]) # he print(3*'pine') # pinepinepine print('like'+'pine') # likepine 通過(guò)+ * 實(shí)現(xiàn)字符串的連接 print(len('apple')) # 5實(shí)例
month='janfebmaraprmayjunaugsepoctnovdec' n=input('please input num(1-12):') pos=3*(int(n)-1) month_abbrev=month[pos:pos+3] print(type(month_abbrev)) print("月份簡(jiǎn)寫為"+month_abbrev+'!')int的問(wèn)題
print(int('1.234')) # 報(bào)錯(cuò) print(eval('1.234'))可以 print(int(1.234)) # 可以字符串的常用方法
實(shí)例
a='thank you' print(a.capitalize()) print(a.center(20)) print(a.center(20,'\'')) print(a.endswith('s')) print(a.find('o')) # 返回第一個(gè)o位置的下標(biāo) 7 print(a.rjust(20,'+'))注意 以上操作都不會(huì)改變a !!! 上述運(yùn)行結(jié)果為
Thank you
???? thank you?????
'''''thank you''''''
False
7? ( 從0 開(kāi)始計(jì)數(shù)的)
+++++++++++thank you
結(jié)果:
tohoaonoko oyooou
thank you
['than', ' you']
thank you
thank yo
thank ywwu
實(shí)例
s='gone with the wind' print(s.find('the')) # 10 找位置 print(s.find('the',4,13)) #找某個(gè)范圍內(nèi)的字符串的位置, 10 s1=['hello','world'] print(' '.join(s1)) # hello world 得到字符串實(shí)例:?'What do you think of the saying "No pains, No gains"?' 中雙引號(hào)的內(nèi)容是否為標(biāo)題格式??
s='What do you think of the saying "No pains, No gains"?' lindex=s.index('\"',0,len(s)) rindex=s.rindex('\"',0,len(s)) s1=s[lindex+1:rindex] print(s1) # No pains, No gains if s1.istitle():print('it is title format') else:print('it is not title format')# 簡(jiǎn)化上述 split s='What do you think of the saying "No pains, No gains"?' s1=s.split('\"')[1] # 用" 隔開(kāi)并取中間的字符串 print(s1) # No pains, No gains if s1.istitle():print('it is title format') else:print('it is not title format')實(shí)例?: 將字符串"hello, world!" 中的world 換成python , 并計(jì)算其包含的標(biāo)點(diǎn)符號(hào)個(gè)數(shù)
s1="hello, world!" s2=s1[:7]+'python!' print(s2) cnt=0 for ch in s2[:]:if ch in ',.?!':cnt=cnt+1 print('there are %d punctuation marks.'%cnt) print('there are {0:d} punctuation marks.'.format(cnt))上述用到了 print輸出的格式化的兩種方法,??第二種中 {} 內(nèi)部的參數(shù)含義是
{參數(shù)的序號(hào):格式說(shuō)明符}
格式說(shuō)明符還有以下這些:? d,f 常用, f 還可規(guī)定 +m.nf 的形式規(guī)定小數(shù)點(diǎn)的個(gè)數(shù)等
整個(gè)寬度是m列, 如果實(shí)際寬度超出了就突破m 的限制
另外還有 < 表示 左對(duì)齊, 默認(rèn)用空格填充
0>5d 表示右對(duì)齊, 用0填充左邊, 寬度為5
^ 居中對(duì)齊
{{}} 表示輸出一個(gè){}
例子
age,height=21,1.783 print("Age:{0:<5d}, Height:{1:5.2f}".format(age,height)) # 上述如果順序是好的, 那么{}第一個(gè)參數(shù)可以不寫0,1,2 # Age:21 , Height: 1.78例子
name=['AXP','BA','CAT','CVX'] price=['100.23','128.34','239.15','309.213'] for i in range(4):print('{:<8d}{:8s}{:8s}'.format(i,name[i],price[i]))# < 左對(duì)齊, 其實(shí)字符串默認(rèn)就是左對(duì)齊, 整數(shù)默認(rèn)方式是右對(duì)齊, 需要用<實(shí)現(xiàn)左對(duì)齊print('I get {:d}{{}}!'.format(32)) # I get 32{}!0? AXP? 100.23
1? BA? ? ?128.34
2? CAT? ?239.15
3? CVX? ?309.213
(3) 元組 tuple? 可以包含多個(gè)數(shù)據(jù)類型,用逗號(hào)分開(kāi),?小括號(hào)括起來(lái)的(a,b,c), 記憶->元組就用圓括號(hào)!!?
tuple('hel') =('h','e','l')
元組的元素不支持賦值, 元組不可變!!
t=(12,'hha',45) t1=12,'hha',45 # 可以不加括號(hào) print(t) print(t1) # (12, 'hha', 45)元組定義后不可以更改了,使程序更安全,但是不靈活,?
t1=(12,) t2=(12) print(type(t1)) # <class 'tuple'> print(type(t2)) # <class 'int'>注意元組定義的逗號(hào)
print(8*(8)) # 64 print(8*(8,)) # (8, 8, 8, 8, 8, 8, 8, 8)sorted(tuple) 報(bào)錯(cuò), 元組不可改變
元組用在什么地方??
(1) 在映射類型中當(dāng)做鍵使用
(2) 函數(shù)的特殊類型參數(shù)
(3) 作為函數(shù)的特殊返回值
可變長(zhǎng)函數(shù)參數(shù)(吸收參數(shù))? 加一個(gè)*,
def fun(x,*y):print(x)print(y) fun('hello','pyhton','world') #hello #('pyhton', 'world') 多個(gè)參數(shù)合并成一個(gè)元組?多個(gè)返回值
def fun():return 1,2,3 fun() #Out[56]: (1, 2, 3)函數(shù)的返回對(duì)象個(gè)數(shù)
(4) list? : Python 中的苦力
元組元素不可變, 但是列表可變!??列表也可以存放不同類型的數(shù)據(jù), 列表用中括號(hào) ,用逗號(hào)分開(kāi) ,列表可更改 [a,b,c]
a=[1,2,3] print(2*a) # [1, 2, 3, 1, 2, 3] 重復(fù)#對(duì)列表進(jìn)行修改 a=[1,2,3] a.append('e') print(a) # [1, 2, 3, 'e'] a.insert(2,10) # 位置2 插入10 print(a) # a改變了, [1, 2, 10, 3, 'e'] a.pop(3) #刪除3位置的元素 print(a) # [1, 2, 10, 'e'] print(a[::-1]) #反向排列 ['e', 10, 2, 1] #a[:] 得到全部 #a[2:] 2位置到最后 a1=a.count(1) # a1=1 計(jì)算1 出現(xiàn)的次數(shù) a=[1,2,3] a.append('e') print(a+a) # 只是連接而已 [1, 2, 3, 'e', 1, 2, 3, 'e'] b=list('ok') print(a+b) # [1, 2, 3, 'e', 'o', 'k'] a=[1,2,13] a.append('e') a.append('b') a.sort(key=lambda x:len(str(x))) # 根據(jù)長(zhǎng)度大小進(jìn)行排序, 不能直接a.sort(key=len) 報(bào)錯(cuò), int沒(méi)有l(wèi)en! print(a) # [1, 2, 'e', 'b', 13] a=[1,2,13] a.append('e') import random as rd a.append('21') rd.shuffle(a) # a改變, 打亂順序 print(a) #[13, 1, 'e', '21', 2]字符串可以變成列表
a='do you like python'.split() print(a) # ['do', 'you', 'like', 'python']實(shí)例: 評(píng)委打分(去掉高低)+ 觀眾打分-->平均分,? ?help(list.sort)?
s1=[9,9,8.5,10,9.4,9.4,8.5,9,8.1,9.1] s2=9 s1.sort() # 從小到大排序 s1.pop() # 去最后一個(gè), 彈出 print(s1) s1.pop(0) s1.append(s2) avg=sum(s1)/len(s1) print('avg score is %.2f'%avg)注意:如果上述用sorted(s1), 不會(huì)改變s1, 通過(guò)賦值可以s3=sorted(s1)
append 與extend對(duì)比
week=['monday','tuesday','wednesday','thursday','friday'] weekend=['saturday','sunday'] #week.append(weekend) #print(week) # ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', ['saturday', 'sunday']] week.extend(weekend) print(week) #['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']for i,j in enumerate(week):print(i+1,j) #1 monday #2 tuesday #3 wednesday #4 thursday #5 friday #6 saturday #7 sundaylist.sort(key=none, reverse=False)
l=[1,2,11,9,4] l.sort(reverse=True) print(l) # [11, 9, 4, 2, 1] s=['apple','egg','banana'] s.sort(key=len) print(s) # ['egg', 'apple', 'banana']列表解析
[x for x in range(5)] Out[49]: [0, 1, 2, 3, 4][x**2 for x in range(5)] Out[50]: [0, 1, 4, 9, 16][x+2 for x in range(10) if x%3==0] Out[51]: [2, 5, 8, 11][(x+1,y+1) for x in range(2) for y in range(3)] Out[52]: [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)](5) dict?:?字典. 字典可以實(shí)現(xiàn)映射, 用花括號(hào) {'a':1, 'b':2}
想要查找某個(gè)人的工資
name=['mike','peter','lily'] sal=[100,200,130] print(sal[name.index('mike')]) # 100上述方式比較復(fù)雜, 字典可以使其更簡(jiǎn)潔,?字典是一種映射類型: 鍵(key)--> 值(value) , key-value 對(duì)
創(chuàng)建字典的方法
#(1) 直接創(chuàng)建 d1={'mike':100, 'allice':120} #(2) 用列表創(chuàng)建 info1=[('mike',100),('alice',120)] # 元素是元組 d2=dict(info1) #(3) info2=[['mike',100],['alice',120]] # 元素是列表 d3=dict(info2) #(4) d4=dict((('mike',100),('alice',120))) # 全部用元組 #(5) d5=dict(mike=100,alice=120)因此, 只要元素之間存在對(duì)應(yīng)關(guān)系, 無(wú)論是tuple ,還是list 都可以創(chuàng)建字典
sorted(d5)
Out[61]: ['alice', 'mike'] ,?字典是無(wú)序存儲(chǔ)的, 這個(gè)只是內(nèi)部存儲(chǔ)結(jié)果
字典的其他創(chuàng)建方法.
d={} # 創(chuàng)立一個(gè)空字典 p=d.fromkeys([1,2,3],'alpha') # 另一種定義字典的方法, key是1,2,3, values一樣都是alpha p={}.fromkeys([1,2,3],'alpha') # 也可以!! print('p=',p) p1=p #p1不隨p變動(dòng) p2=p.copy() #p2不隨p變動(dòng) del p[2] # 刪除2 這個(gè)鍵與值 print ('p=',p) print ('p1=',p1) #p1與p一起變 print ('p2=',p2) #p2不變p= {1: 'alpha', 2: 'alpha', 3: 'alpha'}
p= {1: 'alpha', 3: 'alpha'}
p1= {1: 'alpha', 3: 'alpha'}
p2= {1: 'alpha', 2: 'alpha', 3: 'alpha'}
對(duì)比:?
s={'mike':150, 'alice':180,'bob':200} s1=s s={} # 導(dǎo)致s指向{}, 但是s1不變 print(s1) # {'mike': 150, 'alice': 180, 'bob': 200} s={'mike':150, 'alice':180,'bob':200} s1=s s.clear() # 真的清空了, 被賦值對(duì)象也清空了 print(s1) # {}總結(jié)
注意: 字典是沒(méi)有順序的! 字典不是像list 一樣通過(guò)索引確定對(duì)象 , 而是通過(guò)鍵來(lái)確定
字典的基本操作
p=dict(a=1,b=2,c=3) p Out[66]: {'a': 1, 'b': 2, 'c': 3} p[a] # 出錯(cuò) p['a'] # 查找鍵對(duì)應(yīng)的值 Out[68]: 1 p['d']=4 # 增加新元素 p Out[70]: {'a': 1, 'b': 2, 'c': 3, 'd': 4} 'f' in p # 判斷f 是否在p中 Out[71]: False del p['a'] # 刪除 p Out[73]: {'b': 2, 'c': 3, 'd': 4}注意: 通過(guò)鍵查找值, 推薦使用get?
s={'mike':150, 'allice':180,'bob':200} s['lili'] # 報(bào)錯(cuò) print(s.get('lili')) # 輸出 None , 不報(bào)錯(cuò)實(shí)例
x=['boy','girl'];y=[30,25] #兩個(gè)list z=dict(zip(x,y)) # 利用兩個(gè)list 生成字典 zip()返回zip對(duì)象 print(z) # {'boy': 30, 'girl': 25} print(z.keys()) # dict_keys(['boy', 'girl']) print(z.values()) # dict_values([30, 25]) for m,n in z.items(): # items()返回一個(gè)列表, 元素為鍵值對(duì)構(gòu)成的元組print(m,n) for i in z:print(i) # 默認(rèn)輸出鍵 , 要是遍歷values 則 為 for i in st.values()print(i+':'+str(z[i])) # 鍵:value{'boy': 30, 'girl': 25}
dict_keys(['boy', 'girl'])
dict_values([30, 25])
boy 30
girl 25
boy
boy:30
girl
girl:25
應(yīng)用: 公司簡(jiǎn)稱與對(duì)應(yīng)的股價(jià)提取
s_info=[('AXP','American Express Company','78.61'),('CAT','Caterpillat Inc','98.23')] a=[] b=[] for i in range(2):s1=s_info[i][0]s2=s_info[i][2]a.append(s1)b.append(s2) d=dict(zip(a,b)) print(d) # {'AXP': '78.61', 'CAT': '98.23'}更加簡(jiǎn)便的方法
s_info=[('AXP','American Express Company','78.61'),('CAT','Caterpillat Inc','98.23')] d={} for x in s_info:d[x[0]]=x[2] print(d) # {'AXP': '78.61', 'CAT': '98.23'}實(shí)例3. 現(xiàn)在有兩張工資dict , 一新一舊, 如何更新?
sal1={'mike':100, 'alice':120} sal2={'mike':150, 'alice':180,'bob':200} sal1.update(sal2) print(sal1) # {'mike': 150, 'alice': 180, 'bob': 200}(六) set, 集合.?set可以實(shí)現(xiàn)刪除列表中的相同元素, 用大括號(hào)
{1,2,3} 無(wú)序不重復(fù)
print(set([1,2,3,3,4,5,5])) # {1, 2, 3, 4, 5}快速刪除重復(fù) print (set('you')) #{'y', 'u', 'o'} 用字符串生成set, 每個(gè)元素是字符串的單個(gè)字符 a=set([1,2,3]) a.add('you') a.remove(2) print (a) # {1, 3, 'you'} b=set('abcde') # {'a','b','c','d','e'} c=set('cdefg') print (b&c) # {'e', 'c', 'd'} print (b-c) # {'a', 'b'} print (b^c) #交叉積=b并c-b交c={'a', 'f', 'g', 'b'} print (b|c) # {'a', 'e', 'g', 'c', 'f', 'b', 'd'} print (b.issubset(c)) # 子集的判斷 False b是否為c的子集? d=set('degdeg') print(d<c)# True 判斷集合d在c里面?總結(jié)
? ?
除了上述python 符號(hào), 函數(shù)也能完成以上任務(wù)
??
例如
a=set('sunrise') b=set('sunset') a.issubset(b) Out[89]: False a.difference(b) Out[90]: {'i', 'r'}?例如
a=set('sunrise') a.add('y') print(a) # {'n', 'u', 'y', 'r', 's', 'i', 'e'} a.remove('s') print(a) # {'n', 'u', 'y', 'r', 'i', 'e'} a.update('sunset') print(a) # {'n', 'u', 't', 'y', 'r', 's', 'i', 'e'} a.clear() print(a) # set()?
轉(zhuǎn)載于:https://www.cnblogs.com/xuying-fall/p/8144876.html
總結(jié)
以上是生活随笔為你收集整理的python(1):数据类型/string/list/dict/set等的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 电动车突然没电黑屏是咋回事?
- 下一篇: Python 堡垒机介绍