python 語言基礎二
四、列表 定義 : 一個打了激素的陣列(陣列只能用來存多個同種型別的資料, 但是列表可以儲存多個任意型別的資料) 列表的底層是以 棧 的方式生成的。
列表的方法 : 1. 新增元素 : a = [] print(a) 輸出 : [] append() : 新增一個元素 a.append('xxx') print(a) 輸出 : ['xxx'] print(a.append('yyy')) 輸出 : None extend() : 新增多個元素(必須把要新增的多個元素 放到一個列表中) a.extend(['www', 'qqq']) print(a) 輸出 : ['xxx', 'www', 'qqq'] insert() : 在某位在插入一個元素 a.insert(2, '小明') a.insert(插入的位置, 插入的值) print(a) 輸出 : ['xxx', 'www', '小明', 'qqq']
2. 刪除元素 a = ['hello', '好汙哇有', 'hehe'] print(a) ['hello', '好汙哇有', 'hehe'] remove() : 移除某個元素【如果該元素不存在則報錯(ValueError: list.remove(x): x not in list)】 a.remove('好汙哇有') print(a) ['hello', 'hehe'] del() : 刪除某個下標對應的元素(這個被刪除的元素的引用計數減一),也可以刪除列表 del(a[2]) print(a) ['hello', '好汙哇有'] del(a) print(a) NameError: name 'a' is not defined (a被刪除了導致異常) pop() 彈出一個元素(從列表裡面剔除, 返回值為被剔除的元素),可以指定彈出哪個下標對應的元素, 如果指定的下標不存在則報異常(IndexError: pop index out of range),預設彈出下標最大的元素 b = a.pop(1) print(b) 好汙哇有 print(a) ['hello', 'hehe']
print(a.pop()) hehe
3. 列表切片 a[start:end:步長] 利用索引,我們可以從列表中每次獲取一個元素, 但是如果我們要從列表一次獲取多個元素呢? 此時我們可以使用分片, 分片的結果會得到原列表的一個【拷貝】(不是貼一個標籤!!) a = [0, 1, 2, 3, 4, 5, 6] print(a[1:-1]) [1, 2, 3, 4, 5] 獲取第二個元素到倒數第二個元素這段元素 b = a[1:4:2] print(b) [1, 3] print(a) [0, 1, 2, 3, 4, 5, 6] b[1] = 2 print(b) [1, 2] b已經被改變了 print(a) [0, 1, 2, 3, 4, 5, 6] a沒有被改變
4. 列表的一些常用操作符 a、比較操作符 ( >、 <、 == ) 【當兩個列表中有多個元素時, 預設從第 0 個元素開始比較, 只要有一個元素不相等, 就把這個結果作為列表比較的結果】 list1 = [1, 2, 3, 4 list2 = [2, 2, 3, 4] print(list1 < list2) True print(list1 > list2) False
b、邏輯操作符 ( and、 or、 not)
c、連線操作符 ( + ) 只能連線兩個列表, 如果不是列表, 比如新增是一個數字,就會報 TypeError: can only concatenate list (not "int") to list list1 = [1, 2, 3, 4] list2 = [2, 2, 3, 4] print(list1 + list2) [1, 2, 3, 4, 2, 2, 3, 4] 一般需要新增另一個列表裡的元素時使用 extend() 方法, 而不是使用 + 這個連線操作符
d、重複操作符 ( * ) list1 = [1, 2, 3, 4] print(list1 * 2) [1, 2, 3, 4, 1, 2, 3, 4]
e、成員關係操作符 (in 、not in) 【判斷是否在列表中】 list1 = [1, 2, 3, 4] print(2 in list1) True print(20 in list1) False print([1, 2] in list1) False
5. 獲取列表中的列表 (操作方式類似操作二維陣列)
6. 列表的小夥伴們(內建函式) print(dir(list)) 輸出 : ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
python 中的 . 表示範圍, 比如 list.append() 表示這個 append 函式 是屬於 list 的
append : 新增一個元素
extend :新增多個元素(多個元素放在一個列表中)
insert : 在某位在插入一個元素
clear : 清空列表
pop : 從列表中彈出元素
remove : 移除一個元素
copy : 拷貝列表
count : 統計某元素在列表中出現的次數 list1 = [1, 5, 3] list1 *= 3 print(list1) [1, 5, 3, 1, 5, 3, 1, 5, 3] print(list1.count(1)) 3
index : 獲取某元素出現在列表時的下標(預設是以最小的下標為準, 可以指定查詢 的下標的範圍) list1 = [1, 5, 3] print(list1.index(5)) 1
list1 *= 3 print(list1.index(5)) 1 print(list1) [1, 5, 3, 1, 5, 3, 1, 5, 3] print(list1.index(5, 3, 6)) 4
reverse : 將列表翻轉 (首位順序互換) 【重要】 list1 = [1, 5, 3] print(list1) [1, 5, 3]
list1.reverse() print(list1) [3, 5, 1]
sort : 將列表按從小到大排序 【非常非常重要】 list1 = [1, 5, 3] print(list1) [1, 5, 3] (排序前) list1.sort() print(list1) [1, 3, 5] (排序後)
如果我要從大到小排呢? 方法一: 第一步. 呼叫 sort 排序 第二步.呼叫 reverse 翻轉 方法二: sort 方法有三個引數, list1.sort(func, key|, reverse) 其中 reverse 預設為 False ,表示從小到大排列, 設定為 True 就會從大到小排列了。 list1 = [1, 5, 3] list1.sort(reverse=True) print(list1) [5, 3, 1]
--------------------------------------------------------
五、元組 tuple
由於列表太過靈活, 元素可以順便修改, 現在我們想要一個元素不可變的(列表),這就是元組。 元組的訪問那些跟列表是一樣的。如果我們 想要修改元組中的元素,就會報 TypeError: 'tuple' object does not support item assignment 異常 列表的標誌性符號是 [] 中括號, 那麼元組呢? 我們的第一感覺認為是 () 小括號, 但是事實上是 , 逗號。如下
tuple1 = (1, 2) print(type(tuple1)) <class 'tuple'>
tuple2 = 2, print(type(tuple2)) <class 'tuple'>
tuple3 = (3) print(type(tuple3)) <class 'int'>
----------------------------------------------------------
六、字串
1.各種內建函式 print(dir(str)) 輸出如下 :
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
capitalize : 將首字母大寫 print('hello word'.capitalize()) Hello word
casefold : 將字串全部轉換為小寫 print('HEllo WoRd'.casefold()) hello word
lower : 將字串全部轉換為小寫 print('HEllo WoRd'.casefold()) hello word
center : 將字串的長度填充為 n(原字串居中) str.center(目標長度(小於原長度則什麼都不做) ,用於填充的符號(只能為一個字元)) print('HEllo WoRd'.center(50,'~')) ~~~~~~~~~~~~~~~~~~~~HEllo WoRd~~~~~~~~~~~~~~~~~~~~
ljust : 將字串的長度填充為 n(左對齊) str.ljust(目標長度(小於原長度則什麼都不做) ,用於填充的符號(只能為一個字元)) print('HEllo WoRd'.ljust(50,'~')) HEllo WoRd~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
rjust : 將字串的長度填充為 n(右對齊) str.rjust(目標長度(小於原長度則什麼都不做) ,用於填充的符號(只能為一個字元)) print('HEllo WoRd'.rjust(50,'~')) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~HEllo WoRd
count : 統計某字串出現的次數 print('HEllo WoRd'.count('ll')) 1
encode : 字串編碼格式轉換 print('HEllo WoRd'.encode('utf-8')) b'HEllo WoRd'
【endswith】 : 判斷字串是否以某字元結尾 print('HEllo WoRd'.endswith('sd')) False print('HEllo WoRd'.endswith('Rd')) True print('HEllo WoRd'.endswith('d')) True
【startswith】 : 判斷字串是否以某字元開頭 print('HEllo WoRd'.startswith('sd')) False print('HEllo WoRd'.startswith('H')) True print('HEllo WoRd'.startswith('HE')) True
expandtabs : 把字串中的 tab 符號('\t')轉為空格,tab 符號('\t')預設的空格數是 8。 print('HEllo\tWo\tRd') HEllo Wo Rd print('HEllo\tWo\tRd'.expandtabs()) HEllo Wo Rd
【find】 : 查詢某字串在某區間內出現的下標 (預設區間為整個原字串),沒找到返回 -1 print('HEllo WoRd'.find('o', 5, 8)) 7
index : 查詢某字串在某區間內出現的下標 (預設區間為整個原字串),沒找到拋異常 ValueError: substring not found
isalnum : 檢查字串是否僅僅由字母和數字組成(可以只包含其中一種) print('HElloW2oRd'.isalnum()) True print('HEllo W2oRd'.isalnum()) False print('HElloWoRd'.isalnum()) True print('123'.isalnum()) True
isalpha : 是否全字母 print('HEllo WoRd'.isalpha()) False print('HElloWoRd'.isalpha()) True
isdecimal : 檢查字串是否只包含十進位制字元。這種方法只存在於unicode物件。 print('123 456'.isdecimal()) False print('1234'.isdecimal()) True
isdigit : 檢查字串是否是否全數字 print('123 456'.isdigit()) False print('1234'.isdigit()) True islower : 如果字串中所有的字母都為小寫(可以包含非字母),返回True,否則為False。 print('Hello Word'.islower()) False print('hello word'.islower()) True print('hellowo2rd'.islower()) True print('helloword'.islower()) True istitle : 檢查字串首字母是否為大寫(每個空格隔開一個單詞,檢測一次) print('Hello Word'.istitle()) True print('Hello word'.istitle()) False isupper : 檢查字串字母是否全部為大寫(每個空格隔開一個單詞,檢測一次) print('Hello Word'.isupper()) False print('HELLO WORD'.isupper()) True lstrip : 去掉字串左邊的空格。 print(' HEllo WoRd'.lstrip()) HEllo WoRd strip : 去掉字串開頭和結尾的空格。 print(' HEllo WoRd '.strip()) HEllo WoRd
replace : replace(old,new,count),用new替換old,若使用count引數,則替換次數不超過count次。 print(' HEllo WoRd'.replace(' ', '~', 3)) ~~~HEllo WoRd
【split】 : 將字串按某個字元分割,然後將得到的所有字元都放到列表中返回 print('HEllo WoRd'.split()) ['HEllo', 'WoRd']
【splitlines】 : 將字串按行('\n'回車符)分割,然後將得到的所有字元都放到列表中返回 print('HEllo WoRd \n all body'.splitlines()) ['HEllo WoRd ', ' all body']
swapcase : 將字串中的大寫字元改為小寫,小寫字元改為大寫。 print('HEllo WoRd'.swapcase()) heLLO wOrD
title : 返回標題化的字串(首字母大寫,其他小寫)。 print('hEllo WoRd'.title()) Hello Word
2. 字串格式化 a、 format 內建函式 用法一:只使用 "{}" 符號佔位一個字元 a = 'hello {}' .format('xiaoming') print(a)
用法二:使用多個 "{}" 符號佔位多個字元, 最後按照 format() 裡面的順序對字元進行格式化 b = 'hello {} {}'.format('xaoming', 'xiaohong') print(b)
用法三:使用 "{number}" 大括號包含下標的方式佔位 , 最後按照 format() 裡面的下標格式化到字串裡對應的下標去 c = 'hello {0}、{1}、{3}、{2}'.format('張飛', '趙雲', '馬超', '關羽') 其中可以使用 :加條件對填充進來的值進行格式化, 如下, 四捨五入保留一位小數 print('{0:.1f}'.format(54.56)) 54.6
print(c)
用法四:使用變數 賦值的方式進行佔位, 字串裡面寫 {變數} , format() 裡面寫 變數=值, 最終按照變數名將值格式化到字串裡面去 d = "hello {zhangfei}、{zhaoyun}、{guanyu}".format(zhangfei='張飛',guanyu='關羽', zhaoyun='趙雲') print(d)
注意 : e = "{{0}}".format('hehe') print(e) 如果有兩層花括號, 那麼就不會把 format 裡面的值格式化進去。。。。。。
b、百分號格式化符號 %
格式符為真實值預留位置,並控制顯示的格式。格式符可以包含有一個型別碼,用以控制顯示的型別,如下:
%s 字串 (採用str()的顯示) print('hehe %s' % '幹啥呢') %r 字串 (採用repr()的顯示) hehe 幹啥呢 print('hehe %r' % '幹啥呢') hehe '幹啥呢' %c 單個字元 print('hehe %c' % '幹') hehe 幹 print('hehe %c' % '幹啥呢') TypeError: %c requires int or char %b 二進位制整數 print(b'hello %b' % b'xx') b'hello xx' print('hello %b' % b'xx') ValueError: unsupported format character 'b' (0x62) at index 7 %d 十進位制整數 與 %i 相似 %i 十進位制整數 print('hehe %i' % 50) hehe 50 print('hehe %i' % 0x50) hehe 80 【十六進位制轉10機制展示】 print('hehe %i' % '??') TypeError: %i format: a number is required, not str %o 八進位制整數
%x 十六進位制整數
%e 指數 (基底寫為e)
%E 指數 (基底寫為E)
%f 浮點數
%F 浮點數,與上相同
%g 指數(e)或浮點數 (根據顯示長度)
%G 指數(E)或浮點數 (根據顯示長度)
%% 字元"%"
c、格式化操作符輔助指令
* 定義【寬度或者小數點精度】
- 用做左對齊
+ 在正數前面顯示加號(+)
# 在八進位制數前面顯示零(0),在十六進位制前面顯示"0x"或者"0X"(取決於用的是"x"還是"X")
0 顯示的數字前面填充"0"而不是預設的空格
(var) 對映變數(通常用來處理欄位型別的引數)
m.n 【m 是顯示的最小總寬度】,【n 是小數點後的位數】(如果可用的話)
d、字串轉義字元
\ (在行尾時) 續行符 \\ 反斜槓符號 \' 單引號 \" 雙引號 \a 響鈴 \b 退格(Backspace) \e 轉義 \000 空 \n 換行 \v 縱向製表符 \t 橫向製表符 \r 回車 \f 換頁 \oyy 八進位制數,yy代表的字元,例如:\o12代表換行 \xyy 十六進位制數,yy代表的字元,例如:\x0a代表換行 \other 其它的字元以普通格式輸出
======================================================================================
七、 序列
列表、元組、字串的共同點: 都可以通過索引得到每一個元素 預設索引值總是從0開始 可以通過切片的方法得到一個範圍內的元素的集合 有很多共同的操作符(重複操作符、拼接操作符、成員關係操作符) 所以可以把他們統稱為 【序列】
關於序列常見的內建方法 : 1. list() :把一個可迭代物件轉換為列表
print(help(list)) 輸出 : class list(object) | list() -> new empty list list本身作為一個方法,本身擁有兩種形態, 無引數生成一個空的列表 | list(iterable) -> new list initialized from iterable's items 有引數(引數為一個迭代器):將迭代器中的元素全部取出來作為列表的成員
2. tuple() : 把一個可迭代物件轉換為元組
3. str() : 把一個可迭代物件轉換為字串 a = ['x', 'y', 'yu', 5] print(type(a)) <class 'list'> print(str(a)) ['x', 'y', 'yu', 5] print(type(str(a))) <class 'str'> print(str(a)[0]) [
max() 方法: 求序列中的最大值 【系列中只能包含同種型別的資料才能進行比較】 min() 方法: 求序列中的最小值 【系列中只能包含同種型別的資料才能進行比較】
a = [1, 2, 9, 5, 0, 4] print(max(a)) 輸出 9 print(min(a)) 輸出 0
a = 'zabcdefq' print(max(a)) z print(min(a)) a
a = [1, 2, 9, 5, 0, 4, 'x'] print(max(a)) TypeError: '<' not supported between instances of 'str' and 'int'
sum(iterable[,start=0]) 返回序列器iterable 和可選引數start的總和【序列器只能包含 int 型資料】
a = [1, 5, 8, 9] print(sum(a, 5)) 1 + 5 + 8 + 9 + 5 = 28
sorted(iterable, reverse=False) 對序列進行排序, reverse 預設為 False, 表示從小到大排序 a = [1, 5, 8, 9] print(sorted(a, reverse=True)) [9, 8, 5, 1]
reversed() 用於逆轉一個序列, 返回值為 一個物件。。。可以配合 list 等方法使用 a = [1, 5, 8, 9] print(reversed(a)) <list_reverseiterator object at 0x0000024B92B3C278> print(list(reversed(a))) [9, 8, 5, 1]
enumerate() 列舉, 返回一個物件, 給序列中每一個元素分配一個下標,變成成對的元組 a = [1, 5, 8, 9] print(enumerate(a)) <enumerate object at 0x000001780685C678> print(list(enumerate(a))) [(0, 1), (1, 5), (2, 8), (3, 9)]
zip() 打包, 回一個迭代器物件,將兩個序列下標相同的元素取出組合成一個元組(長度以最短的序列為主) a = [1, 5, 8, 9] b = ('x', 'y', 'z') print(zip(a, b)) <zip object at 0x000001C1704758C8> c = list(zip(a, b)) print(c) [(1, 'x'), (5, 'y'), (8, 'z')] d = [] e = [] for d1, e1 in c: d.append(d1) e.append(e1) print(d) [1, 5, 8] print(e) ['x', 'y', 'z']