python基礎2--資料結構(列表List、元組Tuple、字典Dict)
1、Print函式中文編碼問題
print中的編碼:# -*- coding: utf-8 -*-
注:此處的#代表的是配置資訊
print中的換行符,與C語言相同,為"\n"
2、資料結構List(列表)
# -*- coding: utf-8 -*- #建立List number_list = [1, 3, 5, 7, 9] string_list = ["abc", "bbc", "python"] mixed_list = ['python', 'java', 3, 12] #訪問List中的值 second_num = number_list[1] third_string = string_list[2] fourth_mix = mixed_list[3] print("second_num: {0} third_string: {1} fourth_mix: {2}".format(second_num, third_string, fourth_mix)) #更新List print("number_list before: " + str(number_list)) number_list[1] = 30 print("number_list after: " + str(number_list)) #刪除List元素 print("mixed_list before delete: " + str(mixed_list)) del mixed_list[2] print("mixed_list after delete: " + str(mixed_list)) #Python指令碼語言 print(len([1,2,3])) #長度 print([1,2,3] + [4,5,6]) #組合 print(['Hello'] * 4) #重複 print(3 in [1,2,3]) #某元素是否在列表中 #List的擷取 abcd_list =['a', 'b', 'c', 'd'] print(abcd_list[1]) print(abcd_list[-2]) print(abcd_list[1:]) print(abcd_list[-2:])
執行結果:
列表操作包含以下函式:
(1) cmp(list1, list2):比較兩個列表的元素
(2) len(list):列表元素個數
(3) max(list):返回列表元素最大值
(4) min(list):返回列表元素最小值
(5) list(seq):將元組轉換為列表
列表操作包含以下方法:
(1) list.append(obj):在列表末尾新增新的物件
(2) list.count(obj):統計某個元素在列表中出現的次數
(3) list.extend(seq):在列表末尾一次性追加另一個序列中的多個值(用新列表擴充套件原來的列表)
(4) list.index(obj):從列表中找出某個值第一個匹配項的索引位置
(5) list.insert(index, obj):將物件插入列表
(6) list.pop(obj=list[-1]):移除列表中的一個元素(預設最後一個元素),並且返回該元素的值
(7) list.remove(obj):移除列表中某個值的第一個匹配項
(8) list.reverse():反向列表中元素
(9) list.sort([func]):對原列表進行排序
3、 資料結構Tuple(元組)
#建立只有一個元素的tuple,需要用逗號結尾消除歧義 a_tuple = (2,) #tuple中的list mixed_tuple = (1, 2, ['a', 'b']) print("mixed_tuple: " + str(mixed_tuple)) mixed_tuple[2][0] = 'c' mixed_tuple[2][1] = 'd' print("mixed_tuple: " + str(mixed_tuple))
執行結果:
Tuple是不可變List。一旦建立了一個tuple就不能以任何方式改變它。
Tuple與List的相同之處
定義Tuple與定義List的方式相同, Tuple用, List用方括號。
Tuple的元素與List一樣按定義的次序進行排序。Tuples的索引與List一樣從 0 開始, 所以一個非空Tuple的第一個元素總是 t[0]。
負數索引與List一樣從Tuple的尾部開始計數。
與List一樣分片 (slice) 也可以使用。注意當分割一個 List 時, 會得到一個新的 List ;當分割一個Tuple時, 會得到一個新的Tuple。
Tuple不存在的方法
不能向Tuple增加元素。Tuple沒有append或extend方法。
不能從Tuple刪除元素。Tuple沒有remove或pop方法。
可以使用in來檢視一個元素是否存在於Tuple中。
用Tuple的好處
Tuple比List操作速度快。如果您定義了一個值的常量集,並且唯一要用它做的是不斷地遍歷它,請使用Tuple代替List。
如果對不需要修改的資料進行 “防寫”,可以使程式碼更安全。使用Tuple而不是List如同擁有一個隱含的assert語句,說明這一資料是常量。如果必須要改變這些值,則需要執行Tuple到List的轉換。
Tuple與List的轉換
Tuple可以轉換成List,反之亦然。內建的Tuple函式接收一個List,並返回一個有著相同元素的 Tuple。而 List 函式接收一個Tuple返回一個List。從效果上看,Tuple凍結一個List,而 List解凍一個Tuple。
Tuple的其他應用
一次賦多值
>>> v = ('a', 'b', 'e')
>>> (x, y, z) = v
解釋:v是一個三元素的Tuple, 並且 (x, y, z) 是一個三變數的Tuple。將一個Tuple賦值給另一個Tuple, 會按順序將v 的每個值賦值給每個變數。
4、資料結構Dict(字典)
Dict為key-value鍵值對形式
# -*- coding: utf-8 -*- #建立一個詞典 phone_book = {'Tom': 123, "Jerry": 456, 'Kim': 789} mixed_dict = {"Tom": 'boy', 11: 23.5} #訪問詞典裡的值 print("Tom's number is " + str(phone_book['Tom'])) print('Tom is a ' + mixed_dict['Tom']) #修改詞典 phone_book['Tom'] = 999 phone_book['Heath'] = 888 print("phone_book: " + str(phone_book)) phone_book.update({'Ling':159, 'Lili':247}) print("updated phone_book: " + str(phone_book)) #刪除詞典元素以及詞典本身 del phone_book['Tom'] print("phone_book after deleting Tom: " + str(phone_book)) #清空詞典 phone_book.clear() print("after clear: " + str(phone_book)) #刪除詞典 del phone_book # print("after del: " + str(phone_book)) #不可執行, del後, 字典不存在 #不允許同一個鍵出現兩次 rep_test = {'Name': 'aa', 'age':5, 'Name': 'bb'} print("rep_test: " + str(rep_test)) #可執行, 'Name'為 'bb' #鍵必須不可變,所以可以用書,字串或者元組充當,列表不行 #list_dict = {['Name']: 'John', 'Age':13} #不可執行,list不能當作key,因為list可變 list_dict = {('Name'): 'John', 'Age':13}
字典內建以下函式
(1) cmp(dict1, dict2):比較兩個字典元素。
(2) len(dict):計算字典元素個數,即鍵的總數。
(3) str(dict):輸出字典可列印的字串表示。
(4) type(variable):返回輸入的變數型別,如果變數是字典就返回字典型別。
字典內建以下方法:
(1) radiansdict.clear():刪除字典內所有元素
(2) radiansdict.copy():返回一個字典的淺複製
(3) radiansdict.fromkeys():建立一個新字典,以序列seq中元素做字典的鍵,val為字典所有鍵對應的初始值
(4) radiansdict.get(key, default=None):返回指定鍵的值,如果值不在字典中返回default值
(5) radiansdict.has_key(key):如果鍵在字典dict裡返回true,否則返回false
(6) radiansdict.items():以列表返回可遍歷的(鍵, 值) 元組陣列
(7) radiansdict.keys():以列表返回一個字典所有的鍵
(8) radiansdict.setdefault(key, default=None):和get()類似, 但如果鍵不已經存在於字典中,將會新增鍵並將值設為default
(9) radiansdict.update(dict2):把字典dict2的鍵/值對更新到dict裡
(10) radiansdict.values():以列表返回字典中的所有值