Python开发-- Lesson 2--Python数据类型(2016/07/30)
1、文件操作
-
python中對文件、文件夾(文件操作函數(shù))的操作需要涉及到os模塊和shutil模塊。
得到當前工作目錄,即當前Python腳本工作的目錄路徑:?os.getcwd()
返回指定目錄下的所有文件和目錄名:os.listdir()
函數(shù)用來刪除一個文件:os.remove()
刪除多個目錄:os.removedirs(r“c:\python”)
檢驗給出的路徑是否是一個文件:os.path.isfile()
檢驗給出的路徑是否是一個目錄:os.path.isdir()
判斷是否是絕對路徑:os.path.isabs()
檢驗給出的路徑是否真地存:os.path.exists()
返回一個路徑的目錄名和文件名:os.path.split()???? eg os.path.split('/home/swaroop/byte/code/poem.txt') 結(jié)果:('/home/swaroop/byte/code', 'poem.txt')?
分離擴展名:os.path.splitext()
獲取路徑名:os.path.dirname()
獲取文件名:os.path.basename()
運行shell命令:?os.system()
讀取和設置環(huán)境變量:os.getenv() 與os.putenv()
給出當前平臺使用的行終止符:os.linesep????Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'
指示你正在使用的平臺:os.name?????? 對于Windows,它是'nt',而對于Linux/Unix用戶,它是'posix'
重命名:os.rename(old, new)
創(chuàng)建多級目錄:os.makedirs(r“c:\python\test”)
創(chuàng)建單個目錄:os.mkdir(“test”)
獲取文件屬性:os.stat(file)
修改文件權(quán)限與時間戳:os.chmod(file)
終止當前進程:os.exit()
獲取文件大小:os.path.getsize(filename)
?
- 文件操作:
os.mknod("test.txt")??????? 創(chuàng)建空文件
fp = open("test.txt",w)???? 直接打開一個文件,如果文件不存在則創(chuàng)建文件
關于open 模式:
w?????以寫方式打開,
a?????以追加模式打開 (從 EOF 開始, 必要時創(chuàng)建新文件)
r+?????以讀寫模式打開
w+?????以讀寫模式打開 (參見 w )
a+?????以讀寫模式打開 (參見 a )
rb?????以二進制讀模式打開
wb?????以二進制寫模式打開 (參見 w )
ab?????以二進制追加模式打開 (參見 a )
rb+????以二進制讀寫模式打開 (參見 r+ )
wb+????以二進制讀寫模式打開 (參見 w+ )
ab+????以二進制讀寫模式打開 (參見 a+ )
?
fp.read([size])?????????????????????#size為讀取的長度,以byte為單位
fp.readline([size])???????????????? #讀一行,如果定義了size,有可能返回的只是一行的一部分
fp.readlines([size])??????????????? #把文件每一行作為一個list的一個成員,并返回這個list。其實它的內(nèi)部是通過循環(huán)調(diào)用readline()來實現(xiàn)的。如果提供size參數(shù),size是表示讀取內(nèi)容的總長,也就是說可能只讀到文件的一部分。
fp.write(str)????????????????????? #把str寫到文件中,write()并不會在str后加上一個換行符
fp.writelines(seq)??????????? #把seq的內(nèi)容全部寫到文件中(多行一次性寫入)。這個函數(shù)也只是忠實地寫入,不會在每行后面加上任何東西。
fp.close()??????????????????????? #關閉文件。python會在一個文件不用后自動關閉文件,不過這一功能沒有保證,最好還是養(yǎng)成自己關閉的習慣。? 如果一個文件在關閉后還對其進行操作會產(chǎn)生ValueError
fp.flush()????????????????????????? ? ? ? ? ? ? #把緩沖區(qū)的內(nèi)容寫入硬盤
fp.fileno()??????????????????????????? ????????? #返回一個長整型的”文件標簽“
fp.isatty()????????????????????????????? ??????? #文件是否是一個終端設備文件(unix系統(tǒng)中的)
fp.tell()??????????????????????????????? ? ? ? ?? #返回文件操作標記的當前位置,以文件的開頭為原點
fp.next() ? ??? ? ? ? ? ? ? ? ? ? ????????????? #返回下一行,并將文件操作標記位移到下一行。把一個file用于for … in file這樣的語句時,就是調(diào)用next()函數(shù)來實現(xiàn)遍歷的。
fp.seek(offset[,whence])????????????? #將文件打操作標記移到offset的位置。這個offset一般是相對于文件的開頭來計算的,一般為正數(shù)。但如果提供了whence參數(shù)就不一定了,whence可以為0表示從頭開始計算,1表示以當前位置為原點計算。2表示以文件末尾為原點進行計算。需要注意,如果文件以a或a+的模式打開,每次進行寫操作時,文件操作標記會自動返回到文件末尾。
fp.truncate([size])?????????????????????? #把文件裁成規(guī)定的大小,默認的是裁到當前文件操作標記的位置。如果size比文件的大小還要大,依據(jù)系統(tǒng)的不同可能是不改變文件,也可能是用0把文件補到相應的大小,也可能是以一些隨機的內(nèi)容加上去。
- 目錄操作:
os.mkdir("file")?????????????????? 創(chuàng)建目錄
復制文件:
shutil.copyfile("oldfile","newfile")?????? oldfile和newfile都只能是文件
shutil.copy("oldfile","newfile")??????????? oldfile只能是文件夾,newfile可以是文件,也可以是目標目錄
復制文件夾:
shutil.copytree("olddir","newdir")??????? olddir和newdir都只能是目錄,且newdir必須不存在
重命名文件(目錄)
os.rename("oldname","newname")?????? 文件或目錄都是使用這條命令
移動文件(目錄)
shutil.move("oldpos","newpos") ??
刪除文件
os.remove("file")
刪除目錄
os.rmdir("dir")只能刪除空目錄
shutil.rmtree("dir") ?? 空目錄、有內(nèi)容的目錄都可以刪
轉(zhuǎn)換目錄
os.chdir("path") ??換路徑
with語句
為了避免打開文件后忘記關閉,可以通過管理上下文,即:
?1?with open('log','r') as f:?2?3?...?
如此方式,當with代碼塊執(zhí)行完畢時,內(nèi)部會自動關閉并釋放文件資源。
在Python 2.7 后,with又支持同時對多個文件的上下文進行管理,即:
?1?with open('log1') as obj1, open('log2') as obj2:?2?pass??
- 相關例子?
①、?將文件夾下所有圖片名稱加上'_fc'
python代碼:
1 # -*- coding:utf-8 -*- 2 import re 3 import os 4 import time 5 #str.split(string)分割字符串 6 #'連接符'.join(list) 將列表組成字符串 7 def change_name(path): 8 global i 9 if not os.path.isdir(path) and not os.path.isfile(path): 10 return False 11 if os.path.isfile(path): 12 file_path = os.path.split(path) #分割出目錄與文件 13 lists = file_path[1].split('.') #分割出文件與文件擴展名 14 file_ext = lists[-1] #取出后綴名(列表切片操作) 15 img_ext = ['bmp','jpeg','gif','psd','png','jpg'] 16 if file_ext in img_ext: 17 os.rename(path,file_path[0]+'/'+lists[0]+'_fc.'+file_ext) 18 i+=1 #注意這里的i是一個陷阱 19 #或者 20 #img_ext = 'bmp|jpeg|gif|psd|png|jpg' 21 #if file_ext in img_ext: 22 # print('ok---'+file_ext) 23 elif os.path.isdir(path): 24 for x in os.listdir(path): 25 change_name(os.path.join(path,x)) #os.path.join()在路徑處理上很有用 28 img_dir = 'D:\\xx\\xx\\images' 29 img_dir = img_dir.replace('\\','/') 30 start = time.time() 31 i = 0 32 change_name(img_dir) 33 c = time.time() - start 34 print('程序運行耗時:%0.2f'%(c)) 35 print('總共處理了 %s 張圖片'%(i)) 37 輸出結(jié)果: 39 程序運行耗時:0.11 40 總共處理了 109 張圖片②、
1)打開文件,得到文件句柄并賦值給一個變量
2)通過句柄對文件進行操作
3)關閉文件?
文件
飛鳥與魚代碼
1 f = open('lyrics') #打開文件 2 first_line = f.readline() 3 print('first line:',first_line) #讀一行 4 print('我是分隔線'.center(50,'-')) 5 data = f.read()# 讀取剩下的所有內(nèi)容,文件大時不要用 6 print(data) #打印文件 7 f.close() #關閉文件?
?
?
2、Number(數(shù)字)
Python3 支持?int、float、bool、complex(復數(shù))。
在Python 3里,只有一種整數(shù)類型 int,表示為長整型,沒有 python2 中的 Long。
像大多數(shù)語言一樣,數(shù)值類型的賦值和計算都是很直觀的。
內(nèi)置的type()函數(shù)可以用來查詢變量所指的對象類型。
>>> a, b, c, d = 20, 5.5, True, 4+3j >>> print(type(a), type(b), type(c), type(d)) <class 'int'> <class 'float'> <class 'bool'> <class 'complex'>注意:在Python2中是沒有布爾型的,它用數(shù)字0表示False,用1表示True。到Python3中,把True和False定義成關鍵字了,但它們的值還是1和0,它們可以和數(shù)字相加。
當你指定一個值時,Number 對象就會被創(chuàng)建:
var1 = 1 var2 = 10您也可以使用del語句刪除一些對象引用。
del語句的語法是:
del var1[,var2[,var3[....,varN]]]]您可以通過使用del語句刪除單個或多個對象。例如:
del var del var_a, var_b數(shù)值運算
>>> 5 + 4 # 加法 9 >>> 4.3 - 2 # 減法 2.3 >>> 3 * 7 # 乘法 21 >>> 2 / 4 # 除法,得到一個浮點數(shù) 0.5 >>> 2 // 4 # 除法,得到一個整數(shù) 0 >>> 17 % 3 # 取余 2 >>> 2 ** 5 # 乘方 32注意:
- 1、Python可以同時為多個變量賦值,如a, b = 1, 2。
- 2、一個變量可以通過賦值指向不同類型的對象。
- 3、數(shù)值的除法(/)總是返回一個浮點數(shù),要獲取整數(shù)使用//操作符。
- 4、在混合計算時,Python會把整型轉(zhuǎn)換成為浮點數(shù)。
數(shù)值類型實例
| 10 | 0.0 | 3.14j |
| 100 | 15.20 | 45.j |
| -786 | -21.9 | 9.322e-36j |
| 080 | 32.3+e18 | .876j |
| -0490 | -90. | -.6545+0J |
| -0x260 | -32.54e100 | 3e+26J |
| 0x69 | 70.2-E12 | 4.53e-7j |
Python還支持復數(shù),復數(shù)由實數(shù)部分和虛數(shù)部分構(gòu)成,可以用a + bj,或者complex(a,b)表示, 復數(shù)的實部a和虛部b都是浮點型
3、String(字符串)
Python中的字符串用單引號(')或雙引號(")括起來,同時使用反斜杠(\)轉(zhuǎn)義特殊字符。
字符串的截取的語法格式如下:
變量[頭下標:尾下標]索引值以 0 為開始值,-1 為從末尾的開始位置。
加號 (+) 是字符串的連接符, 星號 (*) 表示復制當前字符串,緊跟的數(shù)字為復制的次數(shù)。實例如下:
#!/usr/bin/python3str = 'Runoob' print (str) # 輸出字符串 print (str[0:-1]) # 輸出第一個個到倒數(shù)第二個的所有字符 print (str[0]) # 輸出字符串第一個字符 print (str[2:5]) # 輸出從第三個開始到第五個的字符 print (str[2:]) # 輸出從第三個開始的后的所有字符 print (str * 2) # 輸出字符串兩次 print (str + "TEST") # 連接字符串執(zhí)行以上程序會輸出如下結(jié)果:
Runoob Runoo R noo noob RunoobRunoob RunoobTESTPython 使用反斜杠(\)轉(zhuǎn)義特殊字符,如果你不想讓反斜杠發(fā)生轉(zhuǎn)義,可以在字符串前面添加一個 r,表示原始字符串:
>>> print('Ru\noob') Ru oob >>> print(r'Ru\noob') Ru\noob >>>另外,反斜杠(\)可以作為續(xù)行符,表示下一行是上一行的延續(xù)。也可以使用?"""..."""?或者?'''...'''?跨越多行。
注意,Python 沒有單獨的字符類型,一個字符就是長度為1的字符串。
>>> word = 'Python' >>> print(word[0], word[5]) P n >>> print(word[-1], word[-6]) n P?
與 C 字符串不同的是,Python 字符串不能被改變。向一個索引位置賦值,比如word[0] = 'm'會導致錯誤。
注意:
- 1、反斜杠可以用來轉(zhuǎn)義,使用r可以讓反斜杠不發(fā)生轉(zhuǎn)義。
- 2、字符串可以用+運算符連接在一起,用*運算符重復。
- 3、Python中的字符串有兩種索引方式,從左往右以0開始,從右往左以-1開始。
- 4、Python中的字符串不能改變。
4、List(列表)
List(列表) 是 Python 中使用最頻繁的數(shù)據(jù)類型。
列表可以完成大多數(shù)集合類的數(shù)據(jù)結(jié)構(gòu)實現(xiàn)。列表中元素的類型可以不相同,它支持數(shù)字,字符串甚至可以包含列表(所謂嵌套)。
列表是寫在方括號([])之間、用逗號分隔開的元素列表。
和字符串一樣,列表同樣可以被索引和截取,列表被截取后返回一個包含所需元素的新列表。
列表截取的語法格式如下:
變量[頭下標:尾下標]索引值以 0 為開始值,-1 為從末尾的開始位置。
加號(+)是列表連接運算符,星號(*)是重復操作。如下實例:
#!/usr/bin/python3list = [ 'abcd', 786 , 2.23, 'runoob', 70.2 ] tinylist = [123, 'runoob'] print (list) # 輸出完整列表 print (list[0]) # 輸出列表第一個元素 print (list[1:3]) # 從第二個開始輸出到第三個元素 print (list[2:]) # 輸出從第三個元素開始的所有元素 print (tinylist * 2) # 輸出兩次列表 print (list + tinylist) # 連接列表以上實例輸出結(jié)果:
['abcd', 786, 2.23, 'runoob', 70.2] abcd [786, 2.23] [2.23, 'runoob', 70.2] [123, 'runoob', 123, 'runoob'] ['abcd', 786, 2.23, 'runoob', 70.2, 123, 'runoob']與Python字符串不一樣的是,列表中的元素是可以改變的:
>>> a = [1, 2, 3, 4, 5, 6] >>> a[0] = 9 >>> a[2:5] = [13, 14, 15] >>> a [9, 2, 13, 14, 15, 6] >>> a[2:5] = [] # 刪除 >>> a [9, 2, 6]List內(nèi)置了有很多方法,例如append()、pop()等等,
?
①?切片?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | name_list?=?["Alex","Tenglan","Eric","Rain","Tom","Amy"] print(name_list[0:3])???????#取下標0至下標3之間的元素,包括0,不包括3 #['Alex', 'Tenglan', 'Eric'] print(name_list[:3])????????#:前什么都不寫,表示從0開始,效果跟上句一樣 #['Alex', 'Tenglan', 'Eric'] print(name_list[3:])????????#:后什么不寫,表示取值到最后 #['Rain', 'Tom', 'Amy'] print(name_list[:])?????????#:前后都不寫,表示取值所有 #['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy'] print(name_list[-3:-1])?????#從-3開始到-1,包括-3,不包括-1 #['Rain', 'Tom'] print(name_list[1:-1])??????#從1開始到-1,下標有正有負時,正數(shù)在前負數(shù)在后 #['Tenglan', 'Eric', 'Rain', 'Tom'] print(name_list[::2])???????#2表示,每個1個元素,就取一個 #['Alex', 'Eric', 'Tom'] #注:[-1:0] [0:0] [-1:2] 都是空 |
?②?追加
| 1 2 3 4 | name_list?=?["Alex","Tenglan","Eric","Rain","Tom","Amy"] name_list.append("new")??????????#append追加,加到最后,只能添加一個 print(name_list) #['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', 'new'] |
③?插入
| 1 2 3 4 | #插入 name_list?=?["Alex","Tenglan","Eric","Rain","Tom","Amy"] name_list.insert(3,"new")??????????#insert插入,把"new"加到下標3的位置 print(name_list) |
④?修改
| 1 2 3 4 | #修改 name_list?=?["Alex","Tenglan","Eric","Rain","Tom","Amy"] name_list[2]?=?"lzl"????????????????#把下標2的字符串換成lzl print(name_list) |
⑤?刪除
| 1 2 3 4 5 6 7 8 9 10 11 | #3種刪除方式 name_list?=?["Alex","Tenglan","Eric","Rain","Tom","Amy"] del?name_list[3]??????????????????????#del刪除,指定要刪除的下標 print(name_list) #['Alex', 'Tenglan', 'Eric', 'Tom', 'Amy'] name_list.remove("Tenglan")??????????#remove刪除,指定要刪除的字符 print(name_list) #['Alex', 'Eric', 'Tom', 'Amy'] name_list.pop()???????????????????????#pop刪除,刪除列表最后一個值 print(name_list) #['Alex', 'Eric', 'Tom'] |
⑥?擴展
| 1 2 3 4 | name_list?=?["Alex","Tenglan","Eric","Rain","Tom","Amy"] age_list?=?[11,22,33] name_list.extend(age_list)???????????????#extend擴展,把列表age_list添加到name_list列表 print(name_list) |
⑦ 拷貝
| 1 2 3 4 | name_list?=?["Alex","Tenglan","Eric","Rain","Tom","Amy"] copy_list?=?name_list.copy()????????????????#copy拷貝,對列表進行復制 print(copy_list) #注:博客最下有關于深淺copy的詳細區(qū)分 |
⑧?統(tǒng)計
| 1 2 3 | name_list?=?["Alex","Tenglan","Eric","Amy","Tom","Amy"] print(name_list.count("Amy"))???????????????#count統(tǒng)計,統(tǒng)計列表Amy的個數(shù) #2 |
⑨?排序和翻轉(zhuǎn)
| 1 2 3 4 5 6 7 | name_list?=?["Alex","Tenglan","Eric","Rain","Tom","Amy","1","2","3"] name_list.sort()??????????????????????????????#sort排序,對列表進行排序 print(name_list) #['1', '2', '3', 'Alex', 'Amy', 'Eric', 'Rain', 'Tenglan', 'Tom'] name_list.reverse()???????????????????????????#reverse翻轉(zhuǎn),對列表進行翻轉(zhuǎn) print(name_list) #['Tom', 'Tenglan', 'Rain', 'Eric', 'Amy', 'Alex', '3', '2', '1'] |
?⑩?獲取下標
| 1 2 3 | name_list?=?["Alex","Tenglan","Eric","Rain","Tom","Amy"] print(name_list.index("Tenglan"))??????????????#index索引,獲取字符的下標 #1 |
擴展
1 class list(object): 2 """ 3 list() -> new empty list 4 list(iterable) -> new list initialized from iterable's items 5 """ 6 def append(self, p_object): # real signature unknown; restored from __doc__ 7 """ L.append(object) -- append object to end """ 8 pass 9 10 def count(self, value): # real signature unknown; restored from __doc__ 11 """ L.count(value) -> integer -- return number of occurrences of value """ 12 return 0 13 14 def extend(self, iterable): # real signature unknown; restored from __doc__ 15 """ L.extend(iterable) -- extend list by appending elements from the iterable """ 16 pass 17 18 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ 19 """ 20 L.index(value, [start, [stop]]) -> integer -- return first index of value. 21 Raises ValueError if the value is not present. 22 """ 23 return 0 24 25 def insert(self, index, p_object): # real signature unknown; restored from __doc__ 26 """ L.insert(index, object) -- insert object before index """ 27 pass 28 29 def pop(self, index=None): # real signature unknown; restored from __doc__ 30 """ 31 L.pop([index]) -> item -- remove and return item at index (default last). 32 Raises IndexError if list is empty or index is out of range. 33 """ 34 pass 35 36 def remove(self, value): # real signature unknown; restored from __doc__ 37 """ 38 L.remove(value) -- remove first occurrence of value. 39 Raises ValueError if the value is not present. 40 """ 41 pass 42 43 def reverse(self): # real signature unknown; restored from __doc__ 44 """ L.reverse() -- reverse *IN PLACE* """ 45 pass 46 47 def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__ 48 """ 49 L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; 50 cmp(x, y) -> -1, 0, 1 51 """ 52 pass 53 54 def __add__(self, y): # real signature unknown; restored from __doc__ 55 """ x.__add__(y) <==> x+y """ 56 pass 57 58 def __contains__(self, y): # real signature unknown; restored from __doc__ 59 """ x.__contains__(y) <==> y in x """ 60 pass 61 62 def __delitem__(self, y): # real signature unknown; restored from __doc__ 63 """ x.__delitem__(y) <==> del x[y] """ 64 pass 65 66 def __delslice__(self, i, j): # real signature unknown; restored from __doc__ 67 """ 68 x.__delslice__(i, j) <==> del x[i:j] 69 70 Use of negative indices is not supported. 71 """ 72 pass 73 74 def __eq__(self, y): # real signature unknown; restored from __doc__ 75 """ x.__eq__(y) <==> x==y """ 76 pass 77 78 def __getattribute__(self, name): # real signature unknown; restored from __doc__ 79 """ x.__getattribute__('name') <==> x.name """ 80 pass 81 82 def __getitem__(self, y): # real signature unknown; restored from __doc__ 83 """ x.__getitem__(y) <==> x[y] """ 84 pass 85 86 def __getslice__(self, i, j): # real signature unknown; restored from __doc__ 87 """ 88 x.__getslice__(i, j) <==> x[i:j] 89 90 Use of negative indices is not supported. 91 """ 92 pass 93 94 def __ge__(self, y): # real signature unknown; restored from __doc__ 95 """ x.__ge__(y) <==> x>=y """ 96 pass 97 98 def __gt__(self, y): # real signature unknown; restored from __doc__ 99 """ x.__gt__(y) <==> x>y """ 100 pass 101 102 def __iadd__(self, y): # real signature unknown; restored from __doc__ 103 """ x.__iadd__(y) <==> x+=y """ 104 pass 105 106 def __imul__(self, y): # real signature unknown; restored from __doc__ 107 """ x.__imul__(y) <==> x*=y """ 108 pass 109 110 def __init__(self, seq=()): # known special case of list.__init__ 111 """ 112 list() -> new empty list 113 list(iterable) -> new list initialized from iterable's items 114 # (copied from class doc) 115 """ 116 pass 117 118 def __iter__(self): # real signature unknown; restored from __doc__ 119 """ x.__iter__() <==> iter(x) """ 120 pass 121 122 def __len__(self): # real signature unknown; restored from __doc__ 123 """ x.__len__() <==> len(x) """ 124 pass 125 126 def __le__(self, y): # real signature unknown; restored from __doc__ 127 """ x.__le__(y) <==> x<=y """ 128 pass 129 130 def __lt__(self, y): # real signature unknown; restored from __doc__ 131 """ x.__lt__(y) <==> x<y """ 132 pass 133 134 def __mul__(self, n): # real signature unknown; restored from __doc__ 135 """ x.__mul__(n) <==> x*n """ 136 pass 137 138 @staticmethod # known case of __new__ 139 def __new__(S, *more): # real signature unknown; restored from __doc__ 140 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 141 pass 142 143 def __ne__(self, y): # real signature unknown; restored from __doc__ 144 """ x.__ne__(y) <==> x!=y """ 145 pass 146 147 def __repr__(self): # real signature unknown; restored from __doc__ 148 """ x.__repr__() <==> repr(x) """ 149 pass 150 151 def __reversed__(self): # real signature unknown; restored from __doc__ 152 """ L.__reversed__() -- return a reverse iterator over the list """ 153 pass 154 155 def __rmul__(self, n): # real signature unknown; restored from __doc__ 156 """ x.__rmul__(n) <==> n*x """ 157 pass 158 159 def __setitem__(self, i, y): # real signature unknown; restored from __doc__ 160 """ x.__setitem__(i, y) <==> x[i]=y """ 161 pass 162 163 def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__ 164 """ 165 x.__setslice__(i, j, y) <==> x[i:j]=y 166 167 Use of negative indices is not supported. 168 """ 169 pass 170 171 def __sizeof__(self): # real signature unknown; restored from __doc__ 172 """ L.__sizeof__() -- size of L in memory, in bytes """ 173 pass 174 175 __hash__ = None 176 177 list 178 179 list View Code?
?
注意:
- 1、與字符串一樣,元組的元素不能修改。
- 2、元組也可以被索引和切片,方法一樣。
- 3、注意構(gòu)造包含0或1個元素的元組的特殊語法規(guī)則。
- 4、元組也可以使用+操作符進行拼接。
5、Set(集合)
集合(set)是一個無序不重復元素的序列。
基本功能是進行成員關系測試和刪除重復元素。
可以使用大括號({})或者 set()函數(shù)創(chuàng)建集合,注意:創(chuàng)建一個空集合必須用 set() 而不是 { },因為 { } 是用來創(chuàng)建一個空字典。
#!/usr/bin/python3student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'} print(student) # 輸出集合,重復的元素被自動去掉 # 成員測試 if('Rose' in student) : print('Rose 在集合中') else : print('Rose 不在集合中') # set可以進行集合運算 a = set('abracadabra') b = set('alacazam') print(a) print(a - b) # a和b的差集 print(a | b) # a和b的并集 print(a & b) # a和b的交集 print(a ^ b) # a和b中不同時存在的元素以上實例輸出結(jié)果:
{'Jack', 'Rose', 'Mary', 'Jim', 'Tom'} Rose 在集合中 {'r', 'b', 'a', 'c', 'd'} {'r', 'b', 'd'} {'a', 'l', 'z', 'b', 'm', 'd', 'r', 'c'} {'a', 'c'} {'l', 'z', 'b', 'm', 'd', 'r'}6、Dictionary(字典)
字典(dictionary)是Python中另一個非常有用的內(nèi)置數(shù)據(jù)類型。
列表是有序的對象結(jié)合,字典是無序的對象集合。兩者之間的區(qū)別在于:字典當中的元素是通過鍵來存取的,而不是通過偏移存取。
字典是一種映射類型,字典用"{ }"標識,它是一個無序的鍵(key) : 值(value)對集合。
鍵(key)必須使用不可變類型。
在同一個字典中,鍵(key)必須是唯一的。
#!/usr/bin/python3dict = {} dict['one'] = "1 - 菜鳥教程" dict[2] = "2 - 菜鳥工具" tinydict = {'name': 'runoob','code':1, 'site': 'www.runoob.com'} print (dict['one']) # 輸出鍵為 'one' 的值 print (dict[2]) # 輸出鍵為 2 的值 print (tinydict) # 輸出完整的字典 print (tinydict.keys()) # 輸出所有鍵 print (tinydict.values()) # 輸出所有值以上實例輸出結(jié)果:
1 - 菜鳥教程 2 - 菜鳥工具 {'name': 'runoob', 'site': 'www.runoob.com', 'code': 1} dict_keys(['name', 'site', 'code']) dict_values(['runoob', 'www.runoob.com', 1])構(gòu)造函數(shù) dict() 可以直接從鍵值對序列中構(gòu)建字典如下:
>>> dict([('Runoob', 1), ('Google', 2), ('Taobao', 3)]) {'Taobao': 3, 'Runoob': 1, 'Google': 2} >>> {x: x**2 for x in (2, 4, 6)} {2: 4, 4: 16, 6: 36} >>> dict(Runoob=1, Google=2, Taobao=3) {'Taobao': 3, 'Runoob': 1, 'Google': 2}另外,字典類型也有一些內(nèi)置的函數(shù),例如clear()、keys()、values()等。
?
2、字典類常用功能:
①?增加
| 1 2 3 | info_dic?=?{'stu1101':?"TengLan Wu",'stu1102':?"LongZe Luola",'stu1103':?"XiaoZe Maliya",} info_dic['stu1104']?=?"JingKong Cang"???????????#增加 print(info_dic) |
?②?修改
| 1 2 3 | info_dic?=?{'stu1101':?"TengLan Wu",'stu1102':?"LongZe Luola",'stu1103':?"XiaoZe Maliya",} info_dic["stu1101"]?=?"Jingkong Cang"?????????#有相應的key時為修改,沒有為增加 print(info_dic) |
③?刪除
| 1 2 3 4 5 6 7 8 9 10 11 12 | #3種刪除方式 info_dic?=?{'stu1101':?"TengLan Wu",'stu1102':?"LongZe Luola",'stu1103':?"XiaoZe Maliya",} info_dic.pop('stu1101')???????????????????????#pop刪除,指定刪除的key print(info_dic) #{'stu1103': 'XiaoZe Maliya', 'stu1102': 'LongZe Luola'} del?info_dic['stu1102']??????????????????????#del刪除,指定刪除的key print(info_dic) #{'stu1103': 'XiaoZe Maliya'} info_dic?=?{'stu1101':?"TengLan Wu",'stu1102':?"LongZe Luola",'stu1103':?"XiaoZe Maliya",} info_dic.popitem()?????????????????????????????#隨機刪除,沒卵用 print(info_dic) #{'stu1101': 'TengLan Wu', 'stu1103': 'XiaoZe Maliya'} |
④?查找value值
| 1 2 3 4 5 | info_dic?=?{'stu1101':?"TengLan Wu",'stu1102':?"LongZe Luola",'stu1103':?"XiaoZe Maliya",} print(info_dic.get('stu1102'))??????????????????#get查找,通過key查找value值 #LongZe Luola print(info_dic['stu1102'])??????????????????????#通過key直接查找,但是如果輸入查找的key不存在的話,就會報錯,get則不會 #LongZe Luola |
⑤?字典多級嵌套
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | av_catalog?=?{ ????"歐美":{ ????????"www.youporn.com": ["很多免費的,世界最大的","質(zhì)量一般"], ????????"www.pornhub.com": ["很多免費的,也很大","質(zhì)量比yourporn高點"], ????????"letmedothistoyou.com": ["多是自拍,高質(zhì)量圖片很多","資源不多,更新慢"], ????????"x-art.com":["質(zhì)量很高,真的很高","全部收費,屌比請繞過"] ????}, ????"日韓":{ ????????"tokyo-hot":["質(zhì)量怎樣不清楚,個人已經(jīng)不喜歡日韓范了","聽說是收費的"] ????}, ????"大陸":{ ????????"1024":["全部免費,真好,好人一生平安","服務器在國外,慢"] ????} } av_catalog["大陸"]["1024"][1]?+=?",可以用爬蟲爬下來" print(av_catalog["大陸"]["1024"]) #['全部免費,真好,好人一生平安', '服務器在國外,慢,可以用爬蟲爬下來'] |
⑥?循環(huán)
| 1 2 3 4 5 6 7 8 9 10 11 | info_dic?=?{'stu1101':?"TengLan Wu",'stu1102':?"LongZe Luola",'stu1103':?"XiaoZe Maliya",} for?stu_nu?in?info_dic: ????print(stu_nu,info_dic[stu_nu])?????????????#循環(huán)默認提取的是key #stu1103 XiaoZe Maliya #stu1101 TengLan Wu #stu1102 LongZe Luola for?k,v?in?info_dic.items():??????????????????#先把dict生成list,數(shù)據(jù)量大的時候費時,不建議使用 ????print(k,v) #stu1103 XiaoZe Maliya #stu1101 TengLan Wu #stu1102 LongZe Luola |
?3、擴展
?
1 class dict(object): 2 """ 3 dict() -> new empty dictionary 4 dict(mapping) -> new dictionary initialized from a mapping object's 5 (key, value) pairs 6 dict(iterable) -> new dictionary initialized as if via: 7 d = {} 8 for k, v in iterable: 9 d[k] = v 10 dict(**kwargs) -> new dictionary initialized with the name=value pairs 11 in the keyword argument list. For example: dict(one=1, two=2) 12 """ 13 14 def clear(self): # real signature unknown; restored from __doc__ 15 """ 清除內(nèi)容 """ 16 """ D.clear() -> None. Remove all items from D. """ 17 pass 18 19 def copy(self): # real signature unknown; restored from __doc__ 20 """ 淺拷貝 """ 21 """ D.copy() -> a shallow copy of D """ 22 pass 23 24 @staticmethod # known case 25 def fromkeys(S, v=None): # real signature unknown; restored from __doc__ 26 """ 27 dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. 28 v defaults to None. 29 """ 30 pass 31 32 def get(self, k, d=None): # real signature unknown; restored from __doc__ 33 """ 根據(jù)key獲取值,d是默認值 """ 34 """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ 35 pass 36 37 def has_key(self, k): # real signature unknown; restored from __doc__ 38 """ 是否有key """ 39 """ D.has_key(k) -> True if D has a key k, else False """ 40 return False 41 42 def items(self): # real signature unknown; restored from __doc__ 43 """ 所有項的列表形式 """ 44 """ D.items() -> list of D's (key, value) pairs, as 2-tuples """ 45 return [] 46 47 def iteritems(self): # real signature unknown; restored from __doc__ 48 """ 項可迭代 """ 49 """ D.iteritems() -> an iterator over the (key, value) items of D """ 50 pass 51 52 def iterkeys(self): # real signature unknown; restored from __doc__ 53 """ key可迭代 """ 54 """ D.iterkeys() -> an iterator over the keys of D """ 55 pass 56 57 def itervalues(self): # real signature unknown; restored from __doc__ 58 """ value可迭代 """ 59 """ D.itervalues() -> an iterator over the values of D """ 60 pass 61 62 def keys(self): # real signature unknown; restored from __doc__ 63 """ 所有的key列表 """ 64 """ D.keys() -> list of D's keys """ 65 return [] 66 67 def pop(self, k, d=None): # real signature unknown; restored from __doc__ 68 """ 獲取并在字典中移除 """ 69 """ 70 D.pop(k[,d]) -> v, remove specified key and return the corresponding value. 71 If key is not found, d is returned if given, otherwise KeyError is raised 72 """ 73 pass 74 75 def popitem(self): # real signature unknown; restored from __doc__ 76 """ 獲取并在字典中移除 """ 77 """ 78 D.popitem() -> (k, v), remove and return some (key, value) pair as a 79 2-tuple; but raise KeyError if D is empty. 80 """ 81 pass 82 83 def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ 84 """ 如果key不存在,則創(chuàng)建,如果存在,則返回已存在的值且不修改 """ 85 """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ 86 pass 87 88 def update(self, E=None, **F): # known special case of dict.update 89 """ 更新 90 {'name':'alex', 'age': 18000} 91 [('name','sbsbsb'),] 92 """ 93 """ 94 D.update([E, ]**F) -> None. Update D from dict/iterable E and F. 95 If E present and has a .keys() method, does: for k in E: D[k] = E[k] 96 If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v 97 In either case, this is followed by: for k in F: D[k] = F[k] 98 """ 99 pass 100 101 def values(self): # real signature unknown; restored from __doc__ 102 """ 所有的值 """ 103 """ D.values() -> list of D's values """ 104 return [] 105 106 def viewitems(self): # real signature unknown; restored from __doc__ 107 """ 所有項,只是將內(nèi)容保存至view對象中 """ 108 """ D.viewitems() -> a set-like object providing a view on D's items """ 109 pass 110 111 def viewkeys(self): # real signature unknown; restored from __doc__ 112 """ D.viewkeys() -> a set-like object providing a view on D's keys """ 113 pass 114 115 def viewvalues(self): # real signature unknown; restored from __doc__ 116 """ D.viewvalues() -> an object providing a view on D's values """ 117 pass 118 119 def __cmp__(self, y): # real signature unknown; restored from __doc__ 120 """ x.__cmp__(y) <==> cmp(x,y) """ 121 pass 122 123 def __contains__(self, k): # real signature unknown; restored from __doc__ 124 """ D.__contains__(k) -> True if D has a key k, else False """ 125 return False 126 127 def __delitem__(self, y): # real signature unknown; restored from __doc__ 128 """ x.__delitem__(y) <==> del x[y] """ 129 pass 130 131 def __eq__(self, y): # real signature unknown; restored from __doc__ 132 """ x.__eq__(y) <==> x==y """ 133 pass 134 135 def __getattribute__(self, name): # real signature unknown; restored from __doc__ 136 """ x.__getattribute__('name') <==> x.name """ 137 pass 138 139 def __getitem__(self, y): # real signature unknown; restored from __doc__ 140 """ x.__getitem__(y) <==> x[y] """ 141 pass 142 143 def __ge__(self, y): # real signature unknown; restored from __doc__ 144 """ x.__ge__(y) <==> x>=y """ 145 pass 146 147 def __gt__(self, y): # real signature unknown; restored from __doc__ 148 """ x.__gt__(y) <==> x>y """ 149 pass 150 151 def __init__(self, seq=None, **kwargs): # known special case of dict.__init__ 152 """ 153 dict() -> new empty dictionary 154 dict(mapping) -> new dictionary initialized from a mapping object's 155 (key, value) pairs 156 dict(iterable) -> new dictionary initialized as if via: 157 d = {} 158 for k, v in iterable: 159 d[k] = v 160 dict(**kwargs) -> new dictionary initialized with the name=value pairs 161 in the keyword argument list. For example: dict(one=1, two=2) 162 # (copied from class doc) 163 """ 164 pass 165 166 def __iter__(self): # real signature unknown; restored from __doc__ 167 """ x.__iter__() <==> iter(x) """ 168 pass 169 170 def __len__(self): # real signature unknown; restored from __doc__ 171 """ x.__len__() <==> len(x) """ 172 pass 173 174 def __le__(self, y): # real signature unknown; restored from __doc__ 175 """ x.__le__(y) <==> x<=y """ 176 pass 177 178 def __lt__(self, y): # real signature unknown; restored from __doc__ 179 """ x.__lt__(y) <==> x<y """ 180 pass 181 182 @staticmethod # known case of __new__ 183 def __new__(S, *more): # real signature unknown; restored from __doc__ 184 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 185 pass 186 187 def __ne__(self, y): # real signature unknown; restored from __doc__ 188 """ x.__ne__(y) <==> x!=y """ 189 pass 190 191 def __repr__(self): # real signature unknown; restored from __doc__ 192 """ x.__repr__() <==> repr(x) """ 193 pass 194 195 def __setitem__(self, i, y): # real signature unknown; restored from __doc__ 196 """ x.__setitem__(i, y) <==> x[i]=y """ 197 pass 198 199 def __sizeof__(self): # real signature unknown; restored from __doc__ 200 """ D.__sizeof__() -> size of D in memory, in bytes """ 201 pass 202 203 __hash__ = None 204 205 dict 206 207 dict View Code?
?
注意:
- 1、字典是一種映射類型,它的元素是鍵值對。
- 2、字典的關鍵字必須為不可變類型,且不能重復。
- 3、創(chuàng)建空字典使用?{ }。
7、Python數(shù)據(jù)類型轉(zhuǎn)換
有時候,我們需要對數(shù)據(jù)內(nèi)置的類型進行轉(zhuǎn)換,數(shù)據(jù)類型的轉(zhuǎn)換,你只需要將數(shù)據(jù)類型作為函數(shù)名即可。
以下幾個內(nèi)置的函數(shù)可以執(zhí)行數(shù)據(jù)類型之間的轉(zhuǎn)換。這些函數(shù)返回一個新的對象,表示轉(zhuǎn)換的值。
| int(x [,base]) | 將x轉(zhuǎn)換為一個整數(shù) |
| float(x) | 將x轉(zhuǎn)換到一個浮點數(shù) |
| complex(real [,imag]) | 創(chuàng)建一個復數(shù) |
| str(x) | 將對象 x 轉(zhuǎn)換為字符串 |
| repr(x) | 將對象 x 轉(zhuǎn)換為表達式字符串 |
| eval(str) | 用來計算在字符串中的有效Python表達式,并返回一個對象 |
| tuple(s) | 將序列 s 轉(zhuǎn)換為一個元組 |
| list(s) | 將序列 s 轉(zhuǎn)換為一個列表 |
| set(s) | 轉(zhuǎn)換為可變集合 |
| dict(d) | 創(chuàng)建一個字典。d 必須是一個序列 (key,value)元組。 |
| frozenset(s) | 轉(zhuǎn)換為不可變集合 |
| chr(x) | 將一個整數(shù)轉(zhuǎn)換為一個字符 |
| unichr(x) | 將一個整數(shù)轉(zhuǎn)換為Unicode字符 |
| ord(x) | 將一個字符轉(zhuǎn)換為它的整數(shù)值 |
| hex(x) | 將一個整數(shù)轉(zhuǎn)換為一個十六進制字符串 |
| oct(x) | 將一個整數(shù)轉(zhuǎn)換為一個八進制字符串 |
?
?
8、字符編碼與轉(zhuǎn)碼
?
1 class dict(object): 2 """ 3 dict() -> new empty dictionary 4 dict(mapping) -> new dictionary initialized from a mapping object's 5 (key, value) pairs 6 dict(iterable) -> new dictionary initialized as if via: 7 d = {} 8 for k, v in iterable: 9 d[k] = v 10 dict(**kwargs) -> new dictionary initialized with the name=value pairs 11 in the keyword argument list. For example: dict(one=1, two=2) 12 """ 13 14 def clear(self): # real signature unknown; restored from __doc__ 15 """ 清除內(nèi)容 """ 16 """ D.clear() -> None. Remove all items from D. """ 17 pass 18 19 def copy(self): # real signature unknown; restored from __doc__ 20 """ 淺拷貝 """ 21 """ D.copy() -> a shallow copy of D """ 22 pass 23 24 @staticmethod # known case 25 def fromkeys(S, v=None): # real signature unknown; restored from __doc__ 26 """ 27 dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. 28 v defaults to None. 29 """ 30 pass 31 32 def get(self, k, d=None): # real signature unknown; restored from __doc__ 33 """ 根據(jù)key獲取值,d是默認值 """ 34 """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ 35 pass 36 37 def has_key(self, k): # real signature unknown; restored from __doc__ 38 """ 是否有key """ 39 """ D.has_key(k) -> True if D has a key k, else False """ 40 return False 41 42 def items(self): # real signature unknown; restored from __doc__ 43 """ 所有項的列表形式 """ 44 """ D.items() -> list of D's (key, value) pairs, as 2-tuples """ 45 return [] 46 47 def iteritems(self): # real signature unknown; restored from __doc__ 48 """ 項可迭代 """ 49 """ D.iteritems() -> an iterator over the (key, value) items of D """ 50 pass 51 52 def iterkeys(self): # real signature unknown; restored from __doc__ 53 """ key可迭代 """ 54 """ D.iterkeys() -> an iterator over the keys of D """ 55 pass 56 57 def itervalues(self): # real signature unknown; restored from __doc__ 58 """ value可迭代 """ 59 """ D.itervalues() -> an iterator over the values of D """ 60 pass 61 62 def keys(self): # real signature unknown; restored from __doc__ 63 """ 所有的key列表 """ 64 """ D.keys() -> list of D's keys """ 65 return [] 66 67 def pop(self, k, d=None): # real signature unknown; restored from __doc__ 68 """ 獲取并在字典中移除 """ 69 """ 70 D.pop(k[,d]) -> v, remove specified key and return the corresponding value. 71 If key is not found, d is returned if given, otherwise KeyError is raised 72 """ 73 pass 74 75 def popitem(self): # real signature unknown; restored from __doc__ 76 """ 獲取并在字典中移除 """ 77 """ 78 D.popitem() -> (k, v), remove and return some (key, value) pair as a 79 2-tuple; but raise KeyError if D is empty. 80 """ 81 pass 82 83 def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ 84 """ 如果key不存在,則創(chuàng)建,如果存在,則返回已存在的值且不修改 """ 85 """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ 86 pass 87 88 def update(self, E=None, **F): # known special case of dict.update 89 """ 更新 90 {'name':'alex', 'age': 18000} 91 [('name','sbsbsb'),] 92 """ 93 """ 94 D.update([E, ]**F) -> None. Update D from dict/iterable E and F. 95 If E present and has a .keys() method, does: for k in E: D[k] = E[k] 96 If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v 97 In either case, this is followed by: for k in F: D[k] = F[k] 98 """ 99 pass 100 101 def values(self): # real signature unknown; restored from __doc__ 102 """ 所有的值 """ 103 """ D.values() -> list of D's values """ 104 return [] 105 106 def viewitems(self): # real signature unknown; restored from __doc__ 107 """ 所有項,只是將內(nèi)容保存至view對象中 """ 108 """ D.viewitems() -> a set-like object providing a view on D's items """ 109 pass 110 111 def viewkeys(self): # real signature unknown; restored from __doc__ 112 """ D.viewkeys() -> a set-like object providing a view on D's keys """ 113 pass 114 115 def viewvalues(self): # real signature unknown; restored from __doc__ 116 """ D.viewvalues() -> an object providing a view on D's values """ 117 pass 118 119 def __cmp__(self, y): # real signature unknown; restored from __doc__ 120 """ x.__cmp__(y) <==> cmp(x,y) """ 121 pass 122 123 def __contains__(self, k): # real signature unknown; restored from __doc__ 124 """ D.__contains__(k) -> True if D has a key k, else False """ 125 return False 126 127 def __delitem__(self, y): # real signature unknown; restored from __doc__ 128 """ x.__delitem__(y) <==> del x[y] """ 129 pass 130 131 def __eq__(self, y): # real signature unknown; restored from __doc__ 132 """ x.__eq__(y) <==> x==y """ 133 pass 134 135 def __getattribute__(self, name): # real signature unknown; restored from __doc__ 136 """ x.__getattribute__('name') <==> x.name """ 137 pass 138 139 def __getitem__(self, y): # real signature unknown; restored from __doc__ 140 """ x.__getitem__(y) <==> x[y] """ 141 pass 142 143 def __ge__(self, y): # real signature unknown; restored from __doc__ 144 """ x.__ge__(y) <==> x>=y """ 145 pass 146 147 def __gt__(self, y): # real signature unknown; restored from __doc__ 148 """ x.__gt__(y) <==> x>y """ 149 pass 150 151 def __init__(self, seq=None, **kwargs): # known special case of dict.__init__ 152 """ 153 dict() -> new empty dictionary 154 dict(mapping) -> new dictionary initialized from a mapping object's 155 (key, value) pairs 156 dict(iterable) -> new dictionary initialized as if via: 157 d = {} 158 for k, v in iterable: 159 d[k] = v 160 dict(**kwargs) -> new dictionary initialized with the name=value pairs 161 in the keyword argument list. For example: dict(one=1, two=2) 162 # (copied from class doc) 163 """ 164 pass 165 166 def __iter__(self): # real signature unknown; restored from __doc__ 167 """ x.__iter__() <==> iter(x) """ 168 pass 169 170 def __len__(self): # real signature unknown; restored from __doc__ 171 """ x.__len__() <==> len(x) """ 172 pass 173 174 def __le__(self, y): # real signature unknown; restored from __doc__ 175 """ x.__le__(y) <==> x<=y """ 176 pass 177 178 def __lt__(self, y): # real signature unknown; restored from __doc__ 179 """ x.__lt__(y) <==> x<y """ 180 pass 181 182 @staticmethod # known case of __new__ 183 def __new__(S, *more): # real signature unknown; restored from __doc__ 184 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 185 pass 186 187 def __ne__(self, y): # real signature unknown; restored from __doc__ 188 """ x.__ne__(y) <==> x!=y """ 189 pass 190 191 def __repr__(self): # real signature unknown; restored from __doc__ 192 """ x.__repr__() <==> repr(x) """ 193 pass 194 195 def __setitem__(self, i, y): # real signature unknown; restored from __doc__ 196 """ x.__setitem__(i, y) <==> x[i]=y """ 197 pass 198 199 def __sizeof__(self): # real signature unknown; restored from __doc__ 200 """ D.__sizeof__() -> size of D in memory, in bytes """ 201 pass 202 203 __hash__ = None 204 205 dict 206 207 dict python2 1 class dict(object): 2 """ 3 dict() -> new empty dictionary 4 dict(mapping) -> new dictionary initialized from a mapping object's 5 (key, value) pairs 6 dict(iterable) -> new dictionary initialized as if via: 7 d = {} 8 for k, v in iterable: 9 d[k] = v 10 dict(**kwargs) -> new dictionary initialized with the name=value pairs 11 in the keyword argument list. For example: dict(one=1, two=2) 12 """ 13 14 def clear(self): # real signature unknown; restored from __doc__ 15 """ 清除內(nèi)容 """ 16 """ D.clear() -> None. Remove all items from D. """ 17 pass 18 19 def copy(self): # real signature unknown; restored from __doc__ 20 """ 淺拷貝 """ 21 """ D.copy() -> a shallow copy of D """ 22 pass 23 24 @staticmethod # known case 25 def fromkeys(S, v=None): # real signature unknown; restored from __doc__ 26 """ 27 dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. 28 v defaults to None. 29 """ 30 pass 31 32 def get(self, k, d=None): # real signature unknown; restored from __doc__ 33 """ 根據(jù)key獲取值,d是默認值 """ 34 """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ 35 pass 36 37 def has_key(self, k): # real signature unknown; restored from __doc__ 38 """ 是否有key """ 39 """ D.has_key(k) -> True if D has a key k, else False """ 40 return False 41 42 def items(self): # real signature unknown; restored from __doc__ 43 """ 所有項的列表形式 """ 44 """ D.items() -> list of D's (key, value) pairs, as 2-tuples """ 45 return [] 46 47 def iteritems(self): # real signature unknown; restored from __doc__ 48 """ 項可迭代 """ 49 """ D.iteritems() -> an iterator over the (key, value) items of D """ 50 pass 51 52 def iterkeys(self): # real signature unknown; restored from __doc__ 53 """ key可迭代 """ 54 """ D.iterkeys() -> an iterator over the keys of D """ 55 pass 56 57 def itervalues(self): # real signature unknown; restored from __doc__ 58 """ value可迭代 """ 59 """ D.itervalues() -> an iterator over the values of D """ 60 pass 61 62 def keys(self): # real signature unknown; restored from __doc__ 63 """ 所有的key列表 """ 64 """ D.keys() -> list of D's keys """ 65 return [] 66 67 def pop(self, k, d=None): # real signature unknown; restored from __doc__ 68 """ 獲取并在字典中移除 """ 69 """ 70 D.pop(k[,d]) -> v, remove specified key and return the corresponding value. 71 If key is not found, d is returned if given, otherwise KeyError is raised 72 """ 73 pass 74 75 def popitem(self): # real signature unknown; restored from __doc__ 76 """ 獲取并在字典中移除 """ 77 """ 78 D.popitem() -> (k, v), remove and return some (key, value) pair as a 79 2-tuple; but raise KeyError if D is empty. 80 """ 81 pass 82 83 def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ 84 """ 如果key不存在,則創(chuàng)建,如果存在,則返回已存在的值且不修改 """ 85 """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ 86 pass 87 88 def update(self, E=None, **F): # known special case of dict.update 89 """ 更新 90 {'name':'alex', 'age': 18000} 91 [('name','sbsbsb'),] 92 """ 93 """ 94 D.update([E, ]**F) -> None. Update D from dict/iterable E and F. 95 If E present and has a .keys() method, does: for k in E: D[k] = E[k] 96 If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v 97 In either case, this is followed by: for k in F: D[k] = F[k] 98 """ 99 pass 100 101 def values(self): # real signature unknown; restored from __doc__ 102 """ 所有的值 """ 103 """ D.values() -> list of D's values """ 104 return [] 105 106 def viewitems(self): # real signature unknown; restored from __doc__ 107 """ 所有項,只是將內(nèi)容保存至view對象中 """ 108 """ D.viewitems() -> a set-like object providing a view on D's items """ 109 pass 110 111 def viewkeys(self): # real signature unknown; restored from __doc__ 112 """ D.viewkeys() -> a set-like object providing a view on D's keys """ 113 pass 114 115 def viewvalues(self): # real signature unknown; restored from __doc__ 116 """ D.viewvalues() -> an object providing a view on D's values """ 117 pass 118 119 def __cmp__(self, y): # real signature unknown; restored from __doc__ 120 """ x.__cmp__(y) <==> cmp(x,y) """ 121 pass 122 123 def __contains__(self, k): # real signature unknown; restored from __doc__ 124 """ D.__contains__(k) -> True if D has a key k, else False """ 125 return False 126 127 def __delitem__(self, y): # real signature unknown; restored from __doc__ 128 """ x.__delitem__(y) <==> del x[y] """ 129 pass 130 131 def __eq__(self, y): # real signature unknown; restored from __doc__ 132 """ x.__eq__(y) <==> x==y """ 133 pass 134 135 def __getattribute__(self, name): # real signature unknown; restored from __doc__ 136 """ x.__getattribute__('name') <==> x.name """ 137 pass 138 139 def __getitem__(self, y): # real signature unknown; restored from __doc__ 140 """ x.__getitem__(y) <==> x[y] """ 141 pass 142 143 def __ge__(self, y): # real signature unknown; restored from __doc__ 144 """ x.__ge__(y) <==> x>=y """ 145 pass 146 147 def __gt__(self, y): # real signature unknown; restored from __doc__ 148 """ x.__gt__(y) <==> x>y """ 149 pass 150 151 def __init__(self, seq=None, **kwargs): # known special case of dict.__init__ 152 """ 153 dict() -> new empty dictionary 154 dict(mapping) -> new dictionary initialized from a mapping object's 155 (key, value) pairs 156 dict(iterable) -> new dictionary initialized as if via: 157 d = {} 158 for k, v in iterable: 159 d[k] = v 160 dict(**kwargs) -> new dictionary initialized with the name=value pairs 161 in the keyword argument list. For example: dict(one=1, two=2) 162 # (copied from class doc) 163 """ 164 pass 165 166 def __iter__(self): # real signature unknown; restored from __doc__ 167 """ x.__iter__() <==> iter(x) """ 168 pass 169 170 def __len__(self): # real signature unknown; restored from __doc__ 171 """ x.__len__() <==> len(x) """ 172 pass 173 174 def __le__(self, y): # real signature unknown; restored from __doc__ 175 """ x.__le__(y) <==> x<=y """ 176 pass 177 178 def __lt__(self, y): # real signature unknown; restored from __doc__ 179 """ x.__lt__(y) <==> x<y """ 180 pass 181 182 @staticmethod # known case of __new__ 183 def __new__(S, *more): # real signature unknown; restored from __doc__ 184 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 185 pass 186 187 def __ne__(self, y): # real signature unknown; restored from __doc__ 188 """ x.__ne__(y) <==> x!=y """ 189 pass 190 191 def __repr__(self): # real signature unknown; restored from __doc__ 192 """ x.__repr__() <==> repr(x) """ 193 pass 194 195 def __setitem__(self, i, y): # real signature unknown; restored from __doc__ 196 """ x.__setitem__(i, y) <==> x[i]=y """ 197 pass 198 199 def __sizeof__(self): # real signature unknown; restored from __doc__ 200 """ D.__sizeof__() -> size of D in memory, in bytes """ 201 pass 202 203 __hash__ = None 204 205 dict 206 207 dict python3?
9、元組
元組其實跟列表差不多,也是存一組數(shù),只不是它一旦創(chuàng)建,便不能再修改,所以又叫只讀列表
語法
| 1 | names?=?("alex","jack","eric") |
它只有2個方法,一個是count,一個是index,完畢。
程序練習?
請閉眼寫出以下程序。
程序:購物車程序
需求:
?
1 #!/usr/bin/env/python 2 import sys,os,getpass 3 product_list=[('crisp',10), 4 ('chocolate',50), 5 ('cake',100), 6 ('tea',10), 7 ('bread',10), 8 ('chicken',60), 9 ('shrimp',200)] #定義產(chǎn)品列表 10 print(product_list) 11 shopping_list = [] #定義購物車列表 12 salary = input("input your salary:") #輸入現(xiàn)有的金額 13 if salary.isdigit(): #判斷輸入的金額是否是數(shù)字 14 salary = int(salary) # 如果是把數(shù)字轉(zhuǎn)換成整型 15 while True: #如果為真 16 print("-------------product list---------------") 17 for index ,item in enumerate(product_list): #遍歷產(chǎn)品列表中的中的數(shù)據(jù),并加上編號。 18 print(index,item) #打印編號和產(chǎn)品列表中的產(chǎn)品 19 user_choice = input("choice the product what you want:") #輸入選購的產(chǎn)品 20 if user_choice.isdigit():#如果用戶選擇的是數(shù)字 21 user_choice=int(user_choice)#把數(shù)字轉(zhuǎn)換成整型 22 if user_choice < len(product_list) and user_choice>=0:#如果選擇的數(shù)字編號小于產(chǎn)品列表的長度并且用戶的選擇的數(shù)字編號大于或等于0 23 p_item = product_list[user_choice] #定義產(chǎn)品列表中被選擇的產(chǎn)品作為一個數(shù)組 24 if p_item[1] <= salary:#如果輸入的產(chǎn)品的價格小于或等于現(xiàn)有資金 25 shopping_list.append(p_item)#購物列表中加一個商品 26 salary-=p_item[1]#現(xiàn)有資金-被選商品的資金傳到salary里 27 print ("Added %s into shopping cart ,your current balance is %d " %(p_item, salary))#打印出添添加的商品和資金 28 else: 29 print("Sorry,Your balance is not enough")#否則提示余額不足 30 else: 31 print("product code [%s] is not exist." % user_choice)# 否則打印出產(chǎn)品不存在 32 elif user_choice == 'q':#其他如果用戶輸入 33 print("----------shopping list--------------")#打印出shopping list 34 for p in shopping_list:# 35 print(p)#循環(huán)打印出shoppinglist 36 print("your current balance: %s " % salary)#打印出你的余額 37 break?
?
轉(zhuǎn)載于:https://www.cnblogs.com/kml777/p/5737297.html
總結(jié)
以上是生活随笔為你收集整理的Python开发-- Lesson 2--Python数据类型(2016/07/30)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于JPA方法名创建自动查询
- 下一篇: js工具类