目錄結構:
1.數值(Number)
1.1 數值類型
Python的數值類型支持整數,浮點數和復數,他們在Python中分別是int,float和complex。
整數和浮點數的表面區別就是是否有小數點,有小數點的就是浮點數,沒有的就是整數。整數可以為任意長度,浮點數只能保留小數點后15位。例如:5是整數,5.0是浮點數。
復數的書寫格式是x+yj,其中x是實數,y是虛數,j是表示復數的字符,例如:2+3j。
a = 5 # Type()返回變量所屬的類型 # Output: <class 'int'> print(type(a)) # isinstance() 是否是某種類型的實例 # Output: True print(isinstance(a,int)) b = 5.0 # Output: <class 'float'> print(type(b)) # Output: True print(isinstance(b,float)) # Output: (8+3j) c = 5 + 3j print(c + 3) # Output: True print(isinstance(c, complex))
上面代碼中,type()函數返回變量所屬的類型,isinstance()函數檢查變量是否屬於指定類型的實例。
數值類型除了10進制,還有2進制、8進制和16進制。在Python中為了表示這些進制,只需要在數值前加上指定的前綴就可以了。
| 進制 | 前綴 |
| 二進制(Binary) | '0b' or '0B' |
| 八進制(Octal) | '0o' or '0O' |
| 十六進制(Hexadecimal) | '0x' or '0X' |
1.2 類型轉化
我們可以把一種數值類型轉化為另一種數值類型,這個過程被稱為類型轉化。
在數值的加、減操作中,只要有一個操作數是浮點數,那么其中的整數就會隱式地轉化為浮點數(自動地)。
例如:
>>> 1 + 2.0 3.0
在Python中還可以使用int(),float(),complex()方法顯式地進行強制類型轉化。
>>> int(12.1) 12 >>> int(-12.1) -12 >>> int(--12.1) 12 >>> float(12) 12.0 >>> float('12.1') 12.1 >>> float('-12.1') -12.1 >>> complex(2) (2+0j) >>> complex(2.1) (2.1+0j) >>> complex('2+3j') (2+3j)
1.3 Python中的Decimal數據類型
Python中的內置類型float並不能精確的存儲所有的小數。這並不只是Python語言中存在的問題,關於更多讀者可以查閱IEEE 754標准。
>>> 1.1 + 2.2 3.3000000000000003
從上面的運算可以看出,我們只需要得到3.3就可以了,然而卻得到了3.3000000000000003,為了解決這個問題,我們可以使用Python的Decimal類。
# 引入Decimal from decimal import Decimal # val的值是Decimal('3.3') val = Decimal('1.1')+Decimal('2.2') # Output:<class 'decimal.Decimal'> print(type(val)) # Output:3.3 print(val)
在使用Decimal類之前,應該先引入decimal模塊。
1.4 Python中的分數
Python還提供了Fractions類,該類可以提供分數操作。在使用Fractions之前,應該先引入fractions模塊。
# 引入Fraction from fractions import Fraction # Output:1/2 print(Fraction(0.5)) # Output:1/3 print(Fraction(1,3)) # Output: 2/3 print(Fraction(1,3) + Fraction(1,3)) # Output: 6/5 print(1 / Fraction(5,6))
當我們給Fraction傳入浮點數時,可能會得到一些沒有用處的結果,這主要是由於浮點數的不精確存儲造成的。為了解決該問題,Fraction類允許我們傳入一個字符串,並且Fraction會把字符串解析成Decimal類型。
from fractions import Fraction # 浮點數不精確存儲造成的問題 # Output:2476979795053773/2251799813685248 print(Fraction(1.1)) # 傳入字符串,Fraction會把字符串解析成Decimal類型,解決了浮點數不精確存儲的問題 # Output:11/10 print(Fraction('1.1'))
1.5 Python中的算術方法
Python提供了math和random模塊,提供了多種的算術運算。
math模塊中的部分方法:
import math # 圓周率 # Output: 3.141592653589793 print(math.pi) # 余弦 # Output: -1.0 print(math.cos(math.pi)) # 指數 # Output: 22026.465794806718 print(math.exp(10)) # 對數 # Output: 3.0 print(math.log10(1000)) # 反正弦 # Output: 1.1752011936438014 print(math.sinh(1)) # 階乘 # Output: 720 print(math.factorial(6))
random模塊中的部分方法:
import random # 隨機獲取[16,20)中的一個整數 # Output: 16 print(random.randrange(10,20)) x = ['a', 'b', 'c', 'd', 'e'] # 隨機獲取一個元素 # Get random choice print(random.choice(x)) # 隨機組織x中的元素順序 # Shuffle x random.shuffle(x) # Print the shuffled x print(x) # [0,1)的隨機值 # Print random element print(random.random())
2.字符串(String)
字符串的創建
Python中的字符串可以由雙引號、單引號或三重引號創建,三重引號既可以包含單行文本,也可以包含多行文本。
例如:
# 單引號可以表示字符串 my_string = 'Hello' print(my_string) # 雙引號可以表示字符串 my_string = "Hello" print(my_string) # 三重引號可以包含多行文本 my_string = '''Hello, welcome''' print(my_string) my_string = """Hello, welcome to the world of Python""" print(my_string)
輸出結果為:
Hello
Hello
Hello,
welcome
Hello, welcome to
the world of Python
字符串的訪問
在python中可以通過下標的方式來訪問字符串。開始的下標是0,結束的下標是字符串的長度減一。當訪問下標越界時,會拋出IndexError錯誤。
Python中的字符串還支持負的下標,-1代表最后一個元素,-2代表倒數第二個元素,....。還可以通過冒號訪問字符串中的一組字符。
str = 'programiz' print('str = ', str) #第一個字符 print('str[0] = ', str[0]) #最后一個字符 print('str[-1] = ', str[-1]) #從下標為1到下標為5(不包括)的字符,[1,5) print('str[1:5] = ', str[1:5]) #從下標為5到下標為-2(不包括)的字符串,[5,-2) print('str[5:-2] = ', str[5:-2])
輸出結果為:
str = programiz str[0] = p str[-1] = z str[1:5] = rogr str[5:-2] = am
字符串的修改
由於字符串是不可更改的,所以任何試圖修改字符串中的值都會引發錯誤。我們只能重新分配一個不同的字符串和之前的字符串具有相同的名稱,以達到修改的效果。
>>> my_string = 'programiz' >>> my_string[5] = 'a' ... TypeError: 'str' object does not support item assignment >>> my_string = 'Python' >>> my_string 'Python'
我們不可刪除和修改字符串中的字符,但是我們可以刪除整個字符串(使用 del 關鍵字)
>>> del my_string[1] ... TypeError: 'str' object doesn't support item deletion >>> del my_string >>> my_string ... NameError: name 'my_string' is not defined
字符串的迭代
使用for loop語句,我們可以循環迭代字符串。
count = 0 for letter in 'Hello World': if(letter == 'l'): count += 1 print(count,'letters found')
還可以使用下標的形式訪問:
index = 0 str = 'Hello World'; for index in range(len(str)): print(str[index])
字符串的成員字符測試
我們可以測試一個字符串是否包含在另一個字符串中,使用關鍵字 in
>>> 'a' in 'program' True >>> 'at' not in 'battle' False
字符串轉換為枚舉對象
enumerate函數返回一個枚舉對象,它包含了鍵值對。
str = 'cold' # enumerate() list_enumerate = list(enumerate(str)) print('list(enumerate(str) = ', list_enumerate)
輸出結果為:
list(enumerate(str) = [(0, 'c'), (1, 'o'), (2, 'l'), (3, 'd')]
字符串的長度
len函數返回字符串的長度
str = 'cold' # Output:len(str) = 4 print('len(str) = ', len(str))
轉義字符
| 轉義字符 | 描述 |
| \\ | 反斜杠 |
| \' | 單括號 |
| \" | 雙括號 |
| \a | 響鈴符 |
| \b | 退格符 |
| \n | 換行符 |
| \r | 回車符 |
| \t | 水平制表符 |
| \v | 垂直制表符 |
| \xHH | 十六進制 |
轉義字符的忽略
行字符串可以忽略字符串中的轉義字符,行字符串的書寫只需要在字符串的最前面加上r或R就可以了。
>>> print("This is \x61 \ngood example") This is a good example >>> print(r"This is \x61 \ngood example") This is \x61 \ngood example
格式字符串
format()在格式字符串中使用地非常廣泛,格式字符串包含大括號{}作為占位符或替換字段,這些字段將被替換。
# default(implicit) order default_order = "{}, {} and {}".format('John','Bill','Sean') print('\n--- Default Order ---') print(default_order) # order using positional argument positional_order = "{1}, {0} and {2}".format('John','Bill','Sean') print('\n--- Positional Order ---') print(positional_order) # order using keyword argument keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean') print('\n--- Keyword Order ---') print(keyword_order)
結果為:
--- Default Order --- John, Bill and Sean --- Positional Order --- Bill, John and Sean --- Keyword Order --- Sean, Bill and John
3.列表(List)
列表是一個有序的數據項集合,可以通過下標訪問符([])來訪問。
3.1 List元素的創建
在Python程序中,列表由方括號創建,列表元素由逗號隔開。
# 空列表 my_list = [] # 整數列表 my_list = [1, 2, 3] # 混合數據類型列表 my_list = [1, "Hello", 3.4] # 將其他的列表作為改列表的子元素 my_list = ["mouse", [8, 4, 6], ['a']]
除了這種傳統的創建方式,還可以有更優雅的創建方式(列表解析),例如:
pow2 = [2 ** x for x in range(10)] # Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] print(pow2)
列表中可以包含多個for或if語句,if語句可以起到過濾子項的作用,下面是一些案例:
>>> pow2 = [2 ** x for x in range(10) if x > 5] >>> pow2 [64, 128, 256, 512] >>> odd = [x for x in range(20) if x % 2 == 1] >>> odd [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] >>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']] ['Python Language', 'Python Programming', 'C Language', 'C Programming']
3.2 List元素的遍歷、增加、刪除和修改
列表的訪問
my_list = ['p','r','o','b','e'] # Output: p print(my_list[0]) # Output: pr print(my_list[0:2]) # Output: e print(my_list[-1]) # Output: prob print(my_list[0,-1])
列表成員測試
可以使用關鍵字key,測試某一項是否在(或不在)列表中
my_list = ['p','r','o','b','l','e','m'] # Output: True print('p' in my_list) # Output: False print('a' in my_list) # Output: True print('c' not in my_list)
列表的遍歷
可以使用for loop方法遍歷列表中的元素
for fruit in ['apple','banana','mango']: print("I like",fruit)
或者
list = ['apple','banana','mango'] for index in range(len(list)): print(list[index])
列表的增加、修改、刪除
列表是可更改的,意味着它的元素可以更改和刪除,這一點和Tuple與String不一樣。
使用=符,修改列表中元素的值
# values odd = [2, 4, 6, 8] # 改變第一個元素的值 odd[0] = 1 # Output: [1, 4, 6, 8] print(odd) # 改變第二個到第四個元素的值 odd[1:4] = [3, 5, 7] # Output: [1, 3, 5, 7] print(odd)
使用+操作符,連接兩個列表。
使用*操作符,重復列表給定的次數。
使用:(切片操作符),插入一組元素到指定的位置。
使用append()方法,添加某一項到列表中。
使用extend()方法,添加幾項到列表中。
使用insert()方法,插入元素到指定的位置。
odd = [1, 3, 5] #apppend()方法 odd.append(7) # Output: [1, 3, 5, 7] print(odd) #extend()方法 odd.extend([9, 11, 13]) # Output: [1, 3, 5, 7, 9, 11, 13] print(odd) odd = [1, 3, 5] # +操作符 # Output: [1, 3, 5, 9, 7, 5] print(odd + [9, 7, 5]) # *操作符 #Output: ["re", "re", "re"] print(["re"] * 3) odd = [1, 9] # insert()方法 odd.insert(1,3) # Output: [1, 3, 9] print(odd) # : 操作符 odd = [1,3, 9] odd[2:2] = [5, 7] # Output: [1, 3, 5, 7, 9] print(odd)
可以使用del關鍵字修改List中一個或一組元素的值。
my_list = ['p', 'r', 'b', 'l', 'e', 'm'] # Output: ['p', 'r', 'b', 'l', 'e', 'm'] print(my_list) # delete multiple items del my_list[1:5] # Output: ['p', 'm'] print(my_list) # delete entire list del my_list # Error: List not defined print(my_list)
使用remove()方法可以移除給定的值,pop()移除給定下標的項。pop()若不提供下標值,則會移除並且返回最后一項,借助這個方法可以像操作棧一樣操作List(先進后出)。
my_list = ['r', 'o', 'b', 'l', 'e', 'm'] # Output: ['r', 'o', 'b', 'l', 'e', 'm'] print(my_list) # Output: 'o' print(my_list.pop(1)) # Output: ['r', 'b', 'l', 'e', 'm'] print(my_list) # Output: 'm' print(my_list.pop()) # Output: ['r', 'b', 'l', 'e'] print(my_list)
3.3 與List關聯的方法
在python中list本身提供了大量的方法,而且python中還有大量的內置方法支持list類型。下面筆者列出一些常見的方法。
List方法
| 函數 | 描述 |
| append() | 添加一個元素到list的末尾 |
| extend() | 將指定的列表元素(或任何可迭代的)添加到當前列表的末尾 |
| insert() | 在指定的下標處插入元素 |
| remove() | 從列表中移除一個元素 |
| pop() | 返回和移除給定下標的元素 |
| clear() | 移除列表中的所有元素 |
| index() | 返回第一個匹配元素的下標 |
| count() | 返回指定元素在列表中出現的次數 |
| sort() | 給list排序,默認以升序排列 |
| reverse() | 反轉list中的所有元素 |
| copy() | 返回該list的副本 |
支持List的部分內置方法
| 方法 | 描述 |
| round() | 舍入給定的數值,返回浮點數。 |
| sum() | 返回列表中所有元素的和 |
| max() | 返回列表的最大值 |
| min() | 返回列表的最小值 |
| all() | 如果列表中的所有元素都為true或list為空,則返回true |
| any() | 如果列表中有一個元素為true,那么返回true.如果列表為空,返回false |
| len() | 返回list的長度 |
4.集合(Set)
Set是一個未排序的數據項集合,每一個元素都必須是唯一的和不可更改的。注意,Set集合本身是可更改的,我們可以從中添加和刪除元素。Set不能通過下標訪問符([])來訪問。
4.1 Set元素的創建
Set集合由花括號{}創建,集合中的元素使用逗號分隔開。Set集合中可以包含任何數量的數據項,它們可以是任何的數據類型(整數、浮點數、元組等等),但是Set集合中的元素都必須是不可更改的,比如:List或Dictionary都是可更改的數據類型,應此不能作為Set的數據項。
# 整數集合 my_set = {1, 2, 3} print(my_set) # 混合類型數據集合 my_set = {1.0, "Hello", (1, 2, 3)} print(my_set)
由於Set集合中不能包含可更改的數據項(比如List和Dictionary),若需要添加可更改的數據類型項,可使用set()構造方法,set()構造方法可將一個可迭代對象轉化為Set集合。
例如:
# Set集合中不存在重復值 # Output: {1, 2, 3, 4} my_set = {1,2,3,4,3,2} print(my_set) # set集合中不能有可更改的數據項 # 這里的 [3, 4] 是一個可更改的List數據對象 # TypeError: unhashable type: 'list' #my_set = {1, 2, [3, 4]} # 使用set構造函數,從List中構造set對象 # Output: {1, 2, 3} my_set = set([1,2,3,2]) print(my_set)
4.2 Set元素的遍歷、增加、刪除和修改
Set元素的遍歷
使用for loop語句可以遍歷集合
>>> for letter in set("apple"): ... print(letter) ... a p e l
或者:
sets = set("apple") for index in range(len(sets)): print(sets[index])
Set元素的增加、修改
Set中的數據項是不可修改的,但是Set集合是可修改的。
添加單個元素可以使用add方法,添加多個元素可以使用update方法
# 初始化Set集合 my_set = {1,3} print(my_set) # set 集合不支持下標 # TypeError: 'set' object does not support indexing # my_set[0] # 使用add方法,添加元素 # Output: {1, 2, 3} my_set.add(2) print(my_set) # 使用update方法,添加多個元素(並且會去重) # Output: {1, 2, 3, 4} my_set.update([2,3,4]) print(my_set) # 使用update方法,添加set和List # Output: {1, 2, 3, 4, 5, 6, 8} my_set.update([4,5], {1,6,8}) print(my_set)
Set元素的刪除
移除Set中元素的值可以使用remove()或discard()方法,這兩個方法都可以移除數據項,它們唯一的區別是:當被移除的數據項不存在時,discard()方法什么也不會做;而remove()方法會拋出異常。
# 初始化my_set my_set = {1, 3, 4, 5, 6} print(my_set) # discard一個元素 # Output: {1, 3, 5, 6} my_set.discard(4) print(my_set) # remove一個元素 # Output: {1, 3, 5} my_set.remove(6) print(my_set) # discard一個不存在的元素 # Output: {1, 3, 5} my_set.discard(2) print(my_set) # remove一個不存在的元素,拋出異常 # Output: KeyError: 2 #my_set.remove(2)
同樣我們也可以使用pop()方法(Sets的pop()方法會彈出Set中的一個隨機元素),彈出指定的元素。clear()清除整個set集合。
4.3 Set的交集、並集、差集操作
Set並集操作

集合A與集合B的並集是兩個集合的所有元素,並集使用|符號,也可以使用union()方法。
# initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use | operator # Output: {1, 2, 3, 4, 5, 6, 7, 8} print(A | B)
Set交集操作

集合A和集合B的交集是兩個集合的重疊部分,交集使用&符號,也可以使用intersection()方法。
# initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use & operator # Output: {4, 5} print(A & B)
Set差集操作

集合A與集合B的差(A-B)由所有屬於A且不屬於B的元素組成的集合,差集使用-符號,也可以使用difference()方法。
# initialize A and B A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} # use - operator on A # Output: {1, 2, 3} print(A - B)
Set對稱差集合

集合A與集合B的對稱差集為集合A與集合B中所有不屬於A∩B的元素的集合,對稱差集使用^符號,也可以使用symmetric_difference()方法
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)
5.元組(Tuple)
Tuple和List非常相似,但Tuple一旦創建后就不能再更改,而List可以更改。元祖同List一樣,也是一個有序的數據項集合,可以通過下標訪問符([])來訪問。
5.1 Tuple元素的創建
元組由一對括號()創建(括號可寫可不寫),元組中的元素由逗號分隔開。
# 空元組 # Output: () my_tuple = () print(my_tuple) # 含有三個整數元素的元組 # Output: (1, 2, 3) my_tuple = (1, 2, 3) print(my_tuple) # 混合數據類型的元組 # Output: (1, "Hello", 3.4) my_tuple = (1, "Hello", 3.4) print(my_tuple) # 元組中嵌套內部元組和List # Output: ("mouse", [8, 4, 6], (1, 2, 3)) my_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) print(my_tuple) # 創建元組不使用括號,稱為:元組包裝 # Output: 3, 4.6, "dog" my_tuple = 3, 4.6, "dog" print(my_tuple) # 元組解包 # Output: # 3 # 4.6 # dog a, b, c = my_tuple print(a) print(b) print(c)
創建單個元素的元組,需要在元素后額外加上逗號,例如:
# 只有括號,my_tuple是字符串類型 # Output: <class 'str'> my_tuple = ("hello") print(type(my_tuple)) # 在元素后加上逗號,my_tuple是元組類型 # Output: <class 'tuple'> my_tuple = ("hello",) print(type(my_tuple)) # 括號可寫可不寫 # Output: <class 'tuple'> my_tuple = "hello", print(type(my_tuple))
5.2 Tuple元素的訪問、遍歷
下標訪問:
my_tuple = ('p','e','r','m','i','t') # Output: 'p' print(my_tuple[0]) # Output: 't' print(my_tuple[5]) # tuple嵌套 n_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) # nested index # Output: 's' print(n_tuple[0][3]) # nested index # Output: 4 print(n_tuple[1][1])
負值下標:
my_tuple = ('p','e','r','m','i','t') # Output: 't' print(my_tuple[-1]) # Output: 'p' print(my_tuple[-6])
訪問元組中的一組子元素:
my_tuple = ('p','r','o','g','r','a','m','i','z') # 從第2個到第4個元素 # Output: ('r', 'o', 'g') print(my_tuple[1:4]) # 從開始到倒數第8個元素 # Output: ('p', 'r') print(my_tuple[:-7]) # 從第8個元素到結束的元素 # Output: ('i', 'z') print(my_tuple[7:]) # 從開始到結束的所有元素 # Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z') print(my_tuple[:])
6.字典(Dictionary)
Dictionary是一個未排序的數據項集合,其它的復合數據結構都只含有值作為它的元素,而dictionary既含有鍵,也含有值。Dictionary雖然是無序的,但是仍然可以使用[]符來訪問鍵值對中的值,只不過[]中接收的參數應該是“鍵”,而並非下標。這里需要和其他的有序數據類型的下標訪問區分開來。
6.1 Dictionary的創建
Dictionary的創建由花括號符號{}完成,其中的元素由逗號隔開,鍵和值由冒號隔開。
Dictionary中的key必需是不可更改的數據類型(string,number,tuple或其他的不可更改的數據類型)
# 空的Dictionary my_dict = {} # 使用integer作為Dictionary的key my_dict = {1: 'apple', 2: 'ball'} # 使用混合數據類型作為Dictionary的key my_dict = {'name': 'John', 1: [2, 4, 3]} # 使用 dict() 構造函數創建Dictionary對象 my_dict = dict({1:'apple', 2:'ball'}) # 從一個包含Tuple的List集合中創建Dictionary my_dict = dict([(1,'apple'), (2,'ball')])
6.2 Dictionary的遍歷、增加、刪除、修改
Dictionary的遍歷
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(i,":",squares[i])
Dictionary的增加、修改
Dictionary是可修改的,所以我們可以添加一個新的數據項或改變數據項中原有的值。如果key已經存在了,那么value將會被更新;如果key不存在,那么一個新的鍵值對將會被添加到Dictionary中。
my_dict = {'name':'Jack', 'age': 26}
# 更新值
my_dict['age'] = 27
#Output: {'age': 27, 'name': 'Jack'}
print(my_dict)
# 添加值
my_dict['address'] = 'Downtown'
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
print(my_dict)
Dictionary元素的刪除和移動
我們可以使用pop()方法從Dictionary中彈出指定的鍵值對,它會返回鍵值對中的值。
popitem()方法可以被用來移除和返回任意數據項(key,value)。
clear()方法可以清除Dictionary中的所有數據。
del關鍵字移除某個數據項或是整個Dictionary集合。
# 創建一個dictionary squares = {1:1, 2:4, 3:9, 4:16, 5:25} # 移除指定的鍵值對,返回值 # Output: 16 print(squares.pop(4)) # Output: {1: 1, 2: 4, 3: 9, 5: 25} print(squares) # 移除一個鍵值對 # Output: (1, 1) print(squares.popitem()) # Output: {2: 4, 3: 9, 5: 25} print(squares) # 刪除一個鍵值對 del squares[5] # Output: {2: 4, 3: 9} print(squares) # 移除所有的數據項 squares.clear() # Output: {} print(squares) # 刪除整個dictionary數據 del squares # Throws Error # print(squares)
7. 有序數據類型(sequence-based data types)
在上面筆者提過有序數據類型和無序數據類型,下面筆者再總結一下。
有序數據類型(sequence-based data type):其內部的元素每個元素都有唯一的序列號,第一個元素對應序列號0,第二個元素對應序列號1....,因此可以通過序列號來操作數據。並不是所有的有序數據類型在內存中都是順序存儲的。
無序數據類型(nonsequence-based data type):無序列號來依次存儲數據中的元素。因此不能通過序列號來操作數據。
有序數據類型包含:string,list,tuple。
無序數據類型包含:set,dictionary
7.1 下標(index)
在使用下標的時候,下標既可以為正數、也可以為負數,還可以為零。
//非負下標
0:對應第一個元素。
1:對應第二個元素。
2:對應第三個元素。
...
//負數下標
-1:對應倒數第一個元素
-2:對應倒數第二個元素
...
7.2 切片(slice)
語法:
s[start:end:stride]
s,表示有序集合。
start,表示有序集合的開始下標(可省略)。
end,表示有序集合的結束下標(可省略)。
stride,遞增步數(可省略,默認為1)。
例如:
ss = "Sammy Shark!"; #Output: Shark print(ss[6:11]) #Output: Sammy print(ss[:5]) #Output: hark! print(ss[7:]) #Output:ark print(ss[-4:-1]) #每次遞增1 #Output:Shark print(ss[6:11:1]) #每次遞增2 #Output:SmySak print(ss[0:12:2]) #每次遞增4 #Output:Sya print(ss[0:12:4]) #Output:Sya print(ss[::4]) #反轉元素,每次遞減1 #Output:!krahS ymmaS print(ss[::-1]) #每次遞減2 #Output:!rh ma print(ss[::-2])
刪除切片元素中的數據
要想刪除切片元素中的數據,可以直接用 del s[:] ,注意不是 del s
>>> b = bytearray(b'x' * 10) >>> b bytearray(b'xxxxxxxxxx') >>> len(b) 10 >>> id(b) # 第一次的內存地址 4322850160 >>> del b[:] # 注意,不是del b. 如果想要篩除切片元素,可以使用del b, 但若只想刪除其中的數據,就使用 del b[:] >>> id(b) # 內存地址和第一次一樣,內存未變動,使用del b[:] 不會引起額外的內存問題 4322850160 >>> len(b) # 切片中的元素已經刪除 0 >>> b bytearray(b'') >>>
參考文章:
