日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python(1):数据类型/string/list/dict/set等

發布時間:2024/10/12 python 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python(1):数据类型/string/list/dict/set等 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本系列文章中, python用的idle是spyder或者pycharm, 兩者都很好用, spyder 是在anaconda 中的, 自帶了很多包可以用,

pycharm 只是個編譯器, 沒有很多包, 但是可以從anaconda 中傳過來, 具體操作可以見我的另一篇博文.

Python2 與python3 語法略有差別.??本系列文章全部針對 python3 以上版本!

spyder 中的快捷鍵: ctrl+1 注釋 , F5 運行,? 上下鍵調用, #注釋,??\表示續行

''' abdfa''' 三引號可以實現換行

一行寫多條語句, 需要用分號;

pycharm中的快捷鍵:??Ctrl + /? ?行注釋/取消行注釋,?

ctrl+D 復制本行到下一行(nice),??ctrl+y 刪除本行 ,?Shift + F10??? 運行,?Shift + F9?? 調試??,ctrl+r 替換? ctrl+f 查找

如果運行的按鈕是灰色的, 需要在倒三角的下拉菜單中

地方選擇一下?

左上角的下拉三角這邊 選擇 python ,同時在script path中找到文件的路徑, 之后就可以了.

?(一) python 基礎知識?

python的代碼極為精簡, 沒有分號, if,for不用對應寫end, 縮進是 代碼的靈魂

區分大小寫? fish 與Fish不同的

v='28C'? 字符串可以單引號也可雙引號 , v[-1]='C' ;??v[0:2] 表示0,1, 取不到2

長度為n的序列索引: 0,1,2,3..n-1, 倒過來為-1,-2,...-n

v[0:-1] 獲取除去最后一個字符串以外的部分;??v[::-1] 倒序

float(v[0:-1]) 將字符串轉化為小數

格式化輸出:? print(' the price is: %.2f yuan'%x)? %.2f表示小數點有兩位

range(10) 表示 0-9 , 取不到10

簡單輸入輸出:? ?price=input('please input a number:')

: input()返回的類型是字符型str, 需要用int(), float()得到數值 , 可以用eval()將input當做表達式來處理.

關鍵字: false, none, true, and as, break...

表達式: **乘方, //整除(得到商), % 取余, ~ , & , | ,? <=, >=, !=,==, not, and, or

增量賦值:? m%=5 表示 m=m%5,?a=a+3等價于a+=3? , 還有m**=2, a/=8??

鏈式賦值: m=n=3.14, 先把3.14賦值給n, 再把n 賦值給m,?

多重賦值: x=1, y=2,可以輸出x,y=(1,2) , x,y=y,x 則馬上交換了順序, 不需要通過第三個變量,? ?其中逗號, 表示元組

可以多個一起賦值:? x,y=1,2 兩個同時賦值

3<4<7 表示 (3<4) and (4<7)?

f=open(r'c:\python\test.py','w'); 或者f=open('c:\\python\\test.py','w');?

錯誤 f=open('c:\python\test.py','w');?

python 自己的內建函數: abs(), bool(), round()四舍五入, int(), divmod(), pow(), float(), chr(), complex(),?dir(), input(), help(),?

輸入dir(__builtins__) 得到所有內建函數名,??help(zip) 查看zip 函數的使用指導.?

(二)六種數據類型

(1) 數值型(int , float , complex復數)

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? 實部, x.conjugate() 獲得共軛

str(123)

x//y商? x%y 余數? divmod(x,y)=(x//y,? x%y)

-10//3=-4, 保證余數是正的,? ?abs(x)

(2) string? 字符串, 可以用單引號, 雙引號, 三引號

print('\'nihao\'') #'nihao' print('\"nihao\"') #"nihao"

\轉義符,?

其他也可以用轉義字符表示

a='\101\t\x41\n' b='\141\t\x61\n' print(a,b) #A A # a a

字符串的索引: 從0 開始計數?

注意, 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 # 三引號可以讓字符串保持原貌 word''' s Out[7]: 'hello\nword's=r'd:\python\test.py' # 原始字符串 s Out[9]: 'd:\\python\\test.py'

實例

a='hello' #也可以 a=''hello'', a='''hello''' print(a[2]) #l print(a[0:2]) # he print(3*'pine') # pinepinepine print('like'+'pine') # likepine 通過+ * 實現字符串的連接 print(len('apple')) # 5

實例

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("月份簡寫為"+month_abbrev+'!')

int的問題

print(int('1.234')) # 報錯 print(eval('1.234'))可以 print(int(1.234)) # 可以

字符串的常用方法

實例

a='thank you' print(a.capitalize()) print(a.center(20)) print(a.center(20,'\'')) print(a.endswith('s')) print(a.find('o')) # 返回第一個o位置的下標 7 print(a.rjust(20,'+'))

注意 以上操作都不會改變a !!! 上述運行結果為

Thank you
???? thank you?????
'''''thank you''''''
False
7? ( 從0 開始計數的)
+++++++++++thank you

a='thank you' b='o'.join(a) # 在a的每個字符中都插入o print(b) print(a) # 不改變a print(a.split('k')) # k作為分割點進行分開 print(a.strip()) # 移除字符串頭尾指定的字符 空則刪除空格 print(a.strip('yu')) print(a.replace('o','ww')) #次序為old, new

結果:

tohoaonoko oyooou
thank you
['than', ' you']
thank you
thank yo
thank ywwu

實例

s='gone with the wind' print(s.find('the')) # 10 找位置 print(s.find('the',4,13)) #找某個范圍內的字符串的位置, 10 s1=['hello','world'] print(' '.join(s1)) # hello world 得到字符串

實例:?'What do you think of the saying "No pains, No gains"?' 中雙引號的內容是否為標題格式??

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')# 簡化上述 split s='What do you think of the saying "No pains, No gains"?' s1=s.split('\"')[1] # 用" 隔開并取中間的字符串 print(s1) # No pains, No gains if s1.istitle():print('it is title format') else:print('it is not title format')

實例?: 將字符串"hello, world!" 中的world 換成python , 并計算其包含的標點符號個數

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輸出的格式化的兩種方法,??第二種中 {} 內部的參數含義是

{參數的序號:格式說明符}

格式說明符還有以下這些:? d,f 常用, f 還可規定 +m.nf 的形式規定小數點的個數等

整個寬度是m列, 如果實際寬度超出了就突破m 的限制

另外還有 < 表示 左對齊, 默認用空格填充

0>5d 表示右對齊, 用0填充左邊, 寬度為5

^ 居中對齊

{{}} 表示輸出一個{}

例子

age,height=21,1.783 print("Age:{0:<5d}, Height:{1:5.2f}".format(age,height)) # 上述如果順序是好的, 那么{}第一個參數可以不寫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]))# < 左對齊, 其實字符串默認就是左對齊, 整數默認方式是右對齊, 需要用<實現左對齊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? 可以包含多個數據類型,用逗號分開,?小括號括起來的(a,b,c), 記憶->元組就用圓括號!!?

tuple('hel') =('h','e','l')

元組的元素不支持賦值, 元組不可變!!

t=(12,'hha',45) t1=12,'hha',45 # 可以不加括號 print(t) print(t1) # (12, 'hha', 45)

元組定義后不可以更改了,使程序更安全,但是不靈活,?

t1=(12,) t2=(12) print(type(t1)) # <class 'tuple'> print(type(t2)) # <class 'int'>

注意元組定義的逗號

print(8*(8)) # 64 print(8*(8,)) # (8, 8, 8, 8, 8, 8, 8, 8)

sorted(tuple) 報錯, 元組不可改變

元組用在什么地方??

(1) 在映射類型中當做鍵使用

(2) 函數的特殊類型參數

(3) 作為函數的特殊返回值

可變長函數參數(吸收參數)? 加一個*,

def fun(x,*y):print(x)print(y) fun('hello','pyhton','world') #hello #('pyhton', 'world') 多個參數合并成一個元組

?多個返回值

def fun():return 1,2,3 fun() #Out[56]: (1, 2, 3)

函數的返回對象個數

(4) list? : Python 中的苦力

元組元素不可變, 但是列表可變!??列表也可以存放不同類型的數據, 列表用中括號 ,用逗號分開 ,列表可更改 [a,b,c]

a=[1,2,3] print(2*a) # [1, 2, 3, 1, 2, 3] 重復#對列表進行修改 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 計算1 出現的次數 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))) # 根據長度大小進行排序, 不能直接a.sort(key=len) 報錯, int沒有len! 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']

實例: 評委打分(去掉高低)+ 觀眾打分-->平均分,? ?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() # 去最后一個, 彈出 print(s1) s1.pop(0) s1.append(s2) avg=sum(s1)/len(s1) print('avg score is %.2f'%avg)

注意:如果上述用sorted(s1), 不會改變s1, 通過賦值可以s3=sorted(s1)

append 與extend對比

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 sunday

list.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?:?字典. 字典可以實現映射, 用花括號 {'a':1, 'b':2}

想要查找某個人的工資

name=['mike','peter','lily'] sal=[100,200,130] print(sal[name.index('mike')]) # 100

上述方式比較復雜, 字典可以使其更簡潔,?字典是一種映射類型: 鍵(key)--> 值(value) , key-value 對

創建字典的方法

#(1) 直接創建 d1={'mike':100, 'allice':120} #(2) 用列表創建 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)

因此, 只要元素之間存在對應關系, 無論是tuple ,還是list 都可以創建字典

sorted(d5)
Out[61]: ['alice', 'mike'] ,?字典是無序存儲的, 這個只是內部存儲結果

字典的其他創建方法.

d={} # 創立一個空字典 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變動 p2=p.copy() #p2不隨p變動 del p[2] # 刪除2 這個鍵與值 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'}

對比:?

s={'mike':150, 'alice':180,'bob':200} s1=s s={} # 導致s指向{}, 但是s1不變 print(s1) # {'mike': 150, 'alice': 180, 'bob': 200} s={'mike':150, 'alice':180,'bob':200} s1=s s.clear() # 真的清空了, 被賦值對象也清空了 print(s1) # {}

總結

注意: 字典是沒有順序的! 字典不是像list 一樣通過索引確定對象 , 而是通過鍵來確定

字典的基本操作

p=dict(a=1,b=2,c=3) p Out[66]: {'a': 1, 'b': 2, 'c': 3} p[a] # 出錯 p['a'] # 查找鍵對應的值 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}

注意: 通過鍵查找值, 推薦使用get?

s={'mike':150, 'allice':180,'bob':200} s['lili'] # 報錯 print(s.get('lili')) # 輸出 None , 不報錯

實例

x=['boy','girl'];y=[30,25] #兩個list z=dict(zip(x,y)) # 利用兩個list 生成字典 zip()返回zip對象 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()返回一個列表, 元素為鍵值對構成的元組print(m,n) for i in z:print(i) # 默認輸出鍵 , 要是遍歷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

應用: 公司簡稱與對應的股價提取

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'}

更加簡便的方法

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'}

實例3. 現在有兩張工資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可以實現刪除列表中的相同元素, 用大括號

{1,2,3} 無序不重復

print(set([1,2,3,3,4,5,5])) # {1, 2, 3, 4, 5}快速刪除重復 print (set('you')) #{'y', 'u', 'o'} 用字符串生成set, 每個元素是字符串的單個字符 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里面

?總結

? ?

除了上述python 符號, 函數也能完成以上任務

??

例如

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()

?

轉載于:https://www.cnblogs.com/xuying-fall/p/8144876.html

總結

以上是生活随笔為你收集整理的python(1):数据类型/string/list/dict/set等的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。