獲得當前工做目錄,即當前Python腳本工做的目錄路徑: os.getcwd()python
返回指定目錄下的全部文件和目錄名:os.listdir()git
函數用來刪除一個文件:os.remove()shell
刪除多個目錄:os.removedirs(r「c:\python」)數組
檢驗給出的路徑是不是一個文件:os.path.isfile()服務器
檢驗給出的路徑是不是一個目錄:os.path.isdir()數據結構
判斷是不是絕對路徑:os.path.isabs()app
檢驗給出的路徑是否真地存:os.path.exists()ide
返回一個路徑的目錄名和文件名:os.path.split() eg os.path.split('/home/swaroop/byte/code/poem.txt') 結果:('/home/swaroop/byte/code', 'poem.txt') 函數
分離擴展名:os.path.splitext()工具
獲取路徑名:os.path.dirname()
獲取文件名:os.path.basename()
運行shell命令: os.system()
讀取和設置環境變量:os.getenv() 與os.putenv()
給出當前平臺使用的行終止符:os.linesep Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'
指示你正在使用的平臺:os.name 對於Windows,它是'nt',而對於Linux/Unix用戶,它是'posix'
重命名:os.rename(old, new)
建立多級目錄:os.makedirs(r「c:\python\test」)
建立單個目錄:os.mkdir(「test」)
獲取文件屬性:os.stat(file)
修改文件權限與時間戳:os.chmod(file)
終止當前進程:os.exit()
獲取文件大小:os.path.getsize(filename)
os.mknod("test.txt") 建立空文件
fp = open("test.txt",w) 直接打開一個文件,若是文件不存在則建立文件
關於open 模式:
w 以寫方式打開,
a 以追加模式打開 (從 EOF 開始, 必要時建立新文件)
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。其實它的內部是經過循環調用readline()來實現的。若是提供size參數,size是表示讀取內容的總長,也就是說可能只讀到文件的一部分。
fp.write(str) #把str寫到文件中,write()並不會在str後加上一個換行符
fp.writelines(seq) #把seq的內容所有寫到文件中(多行一次性寫入)。這個函數也只是忠實地寫入,不會在每行後面加上任何東西。
fp.close() #關閉文件。python會在一個文件不用後自動關閉文件,不過這一功能沒有保證,最好仍是養成本身關閉的習慣。 若是一個文件在關閉後還對其進行操做會產生ValueError
fp.flush() #把緩衝區的內容寫入硬盤
fp.fileno() #返回一個長整型的」文件標籤「
fp.isatty() #文件是不是一個終端設備文件(unix系統中的)
fp.tell() #返回文件操做標記的當前位置,以文件的開頭爲原點
fp.next() #返回下一行,並將文件操做標記位移到下一行。把一個file用於for … in file這樣的語句時,就是調用next()函數來實現遍歷的。
fp.seek(offset[,whence]) #將文件打操做標記移到offset的位置。這個offset通常是相對於文件的開頭來計算的,通常爲正數。但若是提供了whence參數就不必定了,whence能夠爲0表示從頭開始計算,1表示以當前位置爲原點計算。2表示以文件末尾爲原點進行計算。須要注意,若是文件以a或a+的模式打開,每次進行寫操做時,文件操做標記會自動返回到文件末尾。
fp.truncate([size]) #把文件裁成規定的大小,默認的是裁到當前文件操做標記的位置。若是size比文件的大小還要大,依據系統的不一樣多是不改變文件,也多是用0把文件補到相應的大小,也多是以一些隨機的內容加上去。
os.mkdir("file") 建立目錄
複製文件:
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") 空目錄、有內容的目錄均可以刪
轉換目錄
os.chdir("path") 換路徑
with語句
爲了不打開文件後忘記關閉,能夠經過管理上下文,即:
1 with open('log','r') as f: 2 3 ...
如此方式,當with代碼塊執行完畢時,內部會自動關閉並釋放文件資源。
在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 輸出結果: 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()# 讀取剩下的全部內容,文件大時不要用 6 print(data) #打印文件 7 f.close() #關閉文件
Python3 支持 int、float、bool、complex(複數)。
在Python 3裏,只有一種整數類型 int,表示爲長整型,沒有 python2 中的 Long。
像大多數語言同樣,數值類型的賦值和計算都是很直觀的。
內置的type()函數能夠用來查詢變量所指的對象類型。
>>> 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中是沒有布爾型的,它用數字0表示False,用1表示True。到Python3中,把True和False定義成關鍵字了,但它們的值仍是1和0,它們能夠和數字相加。
當你指定一個值時,Number 對象就會被建立:
var1 = 1 var2 = 10
您也可使用del語句刪除一些對象引用。
del語句的語法是:
del var1[,var2[,var3[....,varN]]]]
您能夠經過使用del語句刪除單個或多個對象。例如:
del var del var_a, var_b
>>> 5 + 4 # 加法 9 >>> 4.3 - 2 # 減法 2.3 >>> 3 * 7 # 乘法 21 >>> 2 / 4 # 除法,獲得一個浮點數 0.5 >>> 2 // 4 # 除法,獲得一個整數 0 >>> 17 % 3 # 取餘 2 >>> 2 ** 5 # 乘方 32
注意:
int | float | complex |
---|---|---|
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還支持複數,複數由實數部分和虛數部分構成,能夠用a + bj,或者complex(a,b)表示, 複數的實部a和虛部b都是浮點型
Python中的字符串用單引號(')或雙引號(")括起來,同時使用反斜槓(\)轉義特殊字符。
字符串的截取的語法格式以下:
變量[頭下標:尾下標]
索引值以 0 爲開始值,-1 爲從末尾的開始位置。
加號 (+) 是字符串的鏈接符, 星號 (*) 表示複製當前字符串,緊跟的數字爲複製的次數。實例以下:
#!/usr/bin/python3 str = 'Runoob' print (str) # 輸出字符串 print (str[0:-1]) # 輸出第一個個到倒數第二個的全部字符 print (str[0]) # 輸出字符串第一個字符 print (str[2:5]) # 輸出從第三個開始到第五個的字符 print (str[2:]) # 輸出從第三個開始的後的全部字符 print (str * 2) # 輸出字符串兩次 print (str + "TEST") # 鏈接字符串
執行以上程序會輸出以下結果:
Runoob Runoo R noo noob RunoobRunoob RunoobTEST
Python 使用反斜槓(\)轉義特殊字符,若是你不想讓反斜槓發生轉義,能夠在字符串前面添加一個 r,表示原始字符串:
>>> print('Ru\noob') Ru oob >>> print(r'Ru\noob') Ru\noob >>>
另外,反斜槓(\)能夠做爲續行符,表示下一行是上一行的延續。也可使用 """...""" 或者 '''...''' 跨越多行。
注意,Python 沒有單獨的字符類型,一個字符就是長度爲1的字符串。
>>> word = 'Python' >>> print(word[0], word[5]) P n >>> print(word[-1], word[-6]) n P
與 C 字符串不一樣的是,Python 字符串不能被改變。向一個索引位置賦值,好比word[0] = 'm'會致使錯誤。
注意:
List(列表) 是 Python 中使用最頻繁的數據類型。
列表能夠完成大多數集合類的數據結構實現。列表中元素的類型能夠不相同,它支持數字,字符串甚至能夠包含列表(所謂嵌套)。
列表是寫在方括號([])之間、用逗號分隔開的元素列表。
和字符串同樣,列表一樣能夠被索引和截取,列表被截取後返回一個包含所需元素的新列表。
列表截取的語法格式以下:
變量[頭下標:尾下標]
索引值以 0 爲開始值,-1 爲從末尾的開始位置。
加號(+)是列表鏈接運算符,星號(*)是重複操做。以下實例:
#!/usr/bin/python3 list = [ '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) # 鏈接列表
以上實例輸出結果:
['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內置了有不少方法,例如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,下標有正有負時,正數在前負數在後
#['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的詳細區分
|
⑧ 統計
1
2
3
|
name_list
=
[
"Alex"
,
"Tenglan"
,
"Eric"
,
"Amy"
,
"Tom"
,
"Amy"
]
print
(name_list.count(
"Amy"
))
#count統計,統計列表Amy的個數
#2
|
⑨ 排序和翻轉
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翻轉,對列表進行翻轉
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
注意:
集合(set)是一個無序不重複元素的序列。
基本功能是進行成員關係測試和刪除重複元素。
可使用大括號({})或者 set()函數建立集合,注意:建立一個空集合必須用 set() 而不是 { },由於 { } 是用來建立一個空字典。
#!/usr/bin/python3 student = {'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中不一樣時存在的元素
以上實例輸出結果:
{'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'}
字典(dictionary)是Python中另外一個很是有用的內置數據類型。
列表是有序的對象結合,字典是無序的對象集合。二者之間的區別在於:字典當中的元素是經過鍵來存取的,而不是經過偏移存取。
字典是一種映射類型,字典用"{ }"標識,它是一個無序的鍵(key) : 值(value)對集合。
鍵(key)必須使用不可變類型。
在同一個字典中,鍵(key)必須是惟一的。
#!/usr/bin/python3 dict = {} 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()) # 輸出全部值
以上實例輸出結果:
1 - 菜鳥教程 2 - 菜鳥工具 {'name': 'runoob', 'site': 'www.runoob.com', 'code': 1} dict_keys(['name', 'site', 'code']) dict_values(['runoob', 'www.runoob.com', 1])
構造函數 dict() 能夠直接從鍵值對序列中構建字典以下:
>>> 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}
另外,字典類型也有一些內置的函數,例如clear()、keys()、values()等。
二、字典類經常使用功能:
① 增長
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"
: [
"不少免費的,世界最大的"
,
"質量通常"
],
"www.pornhub.com"
: [
"不少免費的,也很大"
,
"質量比yourporn高點"
],
"letmedothistoyou.com"
: [
"可能是自拍,高質量圖片不少"
,
"資源很少,更新慢"
],
"x-art.com"
:[
"質量很高,真的很高"
,
"所有收費,屌比請繞過"
]
},
"日韓"
:{
"tokyo-hot"
:[
"質量怎樣不清楚,我的已經不喜歡日韓範了"
,
"據說是收費的"
]
},
"大陸"
:{
"1024"
:[
"所有免費,真好,好人一輩子平安"
,
"服務器在國外,慢"
]
}
}
av_catalog[
"大陸"
][
"1024"
][
1
]
+
=
",能夠用爬蟲爬下來"
print
(av_catalog[
"大陸"
][
"1024"
])
#['所有免費,真好,好人一輩子平安', '服務器在國外,慢,能夠用爬蟲爬下來']
|
⑥ 循環
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])
#循環默認提取的是key
#stu1103 XiaoZe Maliya
#stu1101 TengLan Wu
#stu1102 LongZe Luola
for
k,v
in
info_dic.items():
#先把dict生成list,數據量大的時候費時,不建議使用
print
(k,v)
#stu1103 XiaoZe Maliya
#stu1101 TengLan Wu
#stu1102 LongZe Luola
|
三、擴展
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 """ 清除內容 """ 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 """ 根據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不存在,則建立,若是存在,則返回已存在的值且不修改 """ 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 """ 全部項,只是將內容保存至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
注意:
有時候,咱們須要對數據內置的類型進行轉換,數據類型的轉換,你只須要將數據類型做爲函數名便可。
如下幾個內置的函數能夠執行數據類型之間的轉換。這些函數返回一個新的對象,表示轉換的值。
函數 | 描述 |
---|---|
int(x [,base]) |
將x轉換爲一個整數 |
float(x) |
將x轉換到一個浮點數 |
complex(real [,imag]) |
建立一個複數 |
str(x) |
將對象 x 轉換爲字符串 |
repr(x) |
將對象 x 轉換爲表達式字符串 |
eval(str) |
用來計算在字符串中的有效Python表達式,並返回一個對象 |
tuple(s) |
將序列 s 轉換爲一個元組 |
list(s) |
將序列 s 轉換爲一個列表 |
set(s) |
轉換爲可變集合 |
dict(d) |
建立一個字典。d 必須是一個序列 (key,value)元組。 |
frozenset(s) |
轉換爲不可變集合 |
chr(x) |
將一個整數轉換爲一個字符 |
unichr(x) |
將一個整數轉換爲Unicode字符 |
ord(x) |
將一個字符轉換爲它的整數值 |
hex(x) |
將一個整數轉換爲一個十六進制字符串 |
oct(x) |
將一個整數轉換爲一個八進制字符串 |
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 """ 清除內容 """ 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 """ 根據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不存在,則建立,若是存在,則返回已存在的值且不修改 """ 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 """ 全部項,只是將內容保存至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
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 """ 清除內容 """ 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 """ 根據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不存在,則建立,若是存在,則返回已存在的值且不修改 """ 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 """ 全部項,只是將內容保存至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
元組其實跟列表差很少,也是存一組數,只不是它一旦建立,便不能再修改,因此又叫只讀列表
語法
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)] #定義產品列表 10 print(product_list) 11 shopping_list = [] #定義購物車列表 12 salary = input("input your salary:") #輸入現有的金額 13 if salary.isdigit(): #判斷輸入的金額是不是數字 14 salary = int(salary) # 若是是把數字轉換成整型 15 while True: #若是爲真 16 print("-------------product list---------------") 17 for index ,item in enumerate(product_list): #遍歷產品列表中的中的數據,並加上編號。 18 print(index,item) #打印編號和產品列表中的產品 19 user_choice = input("choice the product what you want:") #輸入選購的產品 20 if user_choice.isdigit():#若是用戶選擇的是數字 21 user_choice=int(user_choice)#把數字轉換成整型 22 if user_choice < len(product_list) and user_choice>=0:#若是選擇的數字編號小於產品列表的長度而且用戶的選擇的數字編號大於或等於0 23 p_item = product_list[user_choice] #定義產品列表中被選擇的產品做爲一個數組 24 if p_item[1] <= salary:#若是輸入的產品的價格小於或等於現有資金 25 shopping_list.append(p_item)#購物列表中加一個商品 26 salary-=p_item[1]#現有資金-被選商品的資金傳到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)# 不然打印出產品不存在 32 elif user_choice == 'q':#其餘若是用戶輸入 33 print("----------shopping list--------------")#打印出shopping list 34 for p in shopping_list:# 35 print(p)#循環打印出shoppinglist 36 print("your current balance: %s " % salary)#打印出你的餘額 37 break