Python集合(陣列)
Python程式語言中有四種集合資料型別:
列表(list):是一種有序和可更改的集合,允許有重複成員的
元組(tuple):是一種有序且不可更改的集合,允許有重複成員的
集合(set):是一個無序和無索引的集合,沒有重複成員的。
字典(dict):是一個無序、可變和有索引的集合,沒有重複成員。
一、列表
1. 建立列表
>>> thislist = ["apple", "banana", "cherry"] >>> print (thislist)
2. 訪問成員
['apple', 'banana', 'cherry'] >>> print(thislist[1]) banana >>> print(thislist[-1]) cherry
通過索引號訪問列表項。
負的索引表示從末尾開始,-1表示最後一個成員,-2表示倒數第二個成員,依次類推。
>>> thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] >>> print(thislist[2:5]) ['cherry', 'orange', 'kiwi'] >>> print(thislist[-4:-1]) ['orange', 'kiwi', 'melon']
索引範圍:可以指定範圍的起點和終點來指定索引範圍;指定範圍後,返回值將是包含指定成員的新列表
注:第一項的索引為 0,搜尋將從索引 2(包括)開始,到索引 5(不包括)結束
更改成員值:使用索引號
>>> thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]>>> thislist[1] = "huahua" >>> print(thislist) ['apple', 'huahua', 'cherry', 'orange', 'kiwi', 'melon', 'mango']
3. 遍歷列表
使用for迴圈遍歷列表
>>> thislist = ['apple', 'huahua', 'cherry', 'orange', 'kiwi', 'melon', 'mango'] >>> for x in thislist: ... print(x) ... apple huahua cherry orange kiwi melon mango
4. 檢查成員是否存在使用in關鍵字
>>> thislist = ["apple", "banana", "cherry"] >>> if "apple" in thislist: ... print("Yes, 'apple' is in the fruits list") ... Yes, 'apple' is in the fruits list
5. 列表長度
使用len()方法
>>> thislist = ["apple", "banana", "cherry"] >>> print(len(thislist)) 3
6. 新增專案
使用append()方法
>>> thislist = ["apple", "banana", "cherry"] >>> thislist.append("orange") >>> print(thislist) ['apple', 'banana', 'cherry', 'orange']
要在指定的索引處新增專案,使用insert()方法
>>> thislist = ['apple', 'banana', 'cherry', 'orange'] >>> thislist.insert(1,"melon") >>> print(thislist) ['apple', 'melon', 'banana', 'cherry', 'orange']
7.刪除專案
remove()方法刪除指定的專案
>>> thislist = ['apple', 'banana', 'cherry', 'orange'] >>> thislist.remove("apple") >>> print(thislist) ['banana', 'cherry', 'orange']
pop()方法刪除指定的索引(如果未指定索引,則刪除最後一項)
>>> thislist = ['apple', 'banana', 'cherry', 'orange'] >>> thislist.pop() 'orange' >>> print(thislist) ['apple', 'banana', 'cherry']
del關鍵字刪除指定的索引,也能完整的刪除列表
>>> thislist = ['apple', 'banana', 'cherry', 'orange'] >>> del thislist[1] >>> print(thislist) ['apple', 'cherry', 'orange']
>>> thislist = ['apple', 'banana', 'cherry', 'orange'] >>> del thislist >>> print(thislist) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'thislist' is not defined
clear()清空列表
>>> thislist = ["apple", "banana", "cherry"] >>> thislist.clear() >>> print(thislist) []
8. 複製列表
通過鍵入list2 = list1 來複制列表,因為list2將只是對list1的引用,list1中所做的更改也將自動的在list2中進行。
>>> thislist = ["apple", "banana", "cherry"] >>> thislist2 = thislist >>> thislist2 ['apple', 'banana', 'cherry'] >>> thislist.append("melon") >>> thislist2 ['apple', 'banana', 'cherry', 'melon']
使用內建的list的copy()方法複製列表
>>> thislist = ["apple", "banana", "cherry"] >>> mylist = thislist.copy() >>> print(mylist) ['apple', 'banana', 'cherry'] >>> thislist.pop() 'cherry' >>> print(thislist) ['apple', 'banana'] >>> print(mylist) ['apple', 'banana', 'cherry']
使用內建方法list()方法複製列表
>>> thislist = ["apple", "banana", "cherry"] >>> mylist = list(thislist) >>> print(mylist) ['apple', 'banana', 'cherry']
9. 合併兩個列表
最簡單的方法是使用+運算子
>>> list1 = ["a", "b" , "c"] >>> list2 = [1, 2, 3] >>> list3 = list1 + list2 >>> print(list3) ['a', 'b', 'c', 1, 2, 3]
連線兩個列表的方法,將list2中的所有項一個接一個的追加到list1中
>>> list1 = ["a", "b" , "c"] >>> list2 = [1, 2, 3] >>> for x in list2: ... list1.append(x) ... >>> print(list1) ['a', 'b', 'c', 1, 2, 3]
也可以使用extend()方法,將一個列表中的元素新增到另一個列表中
>>> list1 = ["a", "b" , "c"] >>> list2 = [1, 2, 3] >>> list1.extend(list2) >>> print(list1) ['a', 'b', 'c', 1, 2, 3]
10. list()建構函式
建立一個新的列表
>>> thislist = list(("apple", "banana", "cherry")) >>> print(thislist) ['apple', 'banana', 'cherry']
11. 列表的方法
方法 |
描述 |
在列表的末尾新增一個元素 |
|
刪除列表中的所有元素 |
|
返回列表的副本 |
|
返回具有指定值的元素數量。 |
|
將列表元素(或任何可迭代的元素)新增到當前列表的末尾 |
|
返回具有指定值的第一個元素的索引 |
|
在指定位置新增元素 |
|
刪除指定位置的元素 |
|
刪除具有指定值的專案 |
|
顛倒列表的順序 |
|
sort() |
對列表進行排序 |
二、元組
1.建立元組
2.訪問元組專案
>>> thistuple = ("apple", "banana", "cherry") >>> print(thistuple) ('apple', 'banana', 'cherry') >>> print(thistuple[1]) banana >>> print(thistuple[-1]) cherry >>> thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") >>> print(thistuple[2:5]) ('cherry', 'orange', 'kiwi') >>> print(thistuple[-4:-1]) ('orange', 'kiwi', 'melon')
3.更改元組值
注:建立元組後,無法更改其值。元組是不可變的,或者也稱為恆定的。
但是有一種解決方法:可以將元組轉換為列表,更改列表,然後將列表轉換回元組
>>> x = ("apple", "banana", "cherry") >>> y = list(x) >>> y[1] = "kiwi" >>> x = tuple(y) >>> print(x) ('apple', 'kiwi', 'cherry')
4.遍歷元組
>>> thistuple = ("apple", "banana", "cherry") >>> for x in thistuple: ... print(x) ... apple banana cherry
>>> thistuple = ("apple", "banana", "cherry") >>> if "apple" in thistuple: ... print("yes,apple is in thistuple") ... else: ... print("no,apple is not thistuple") ... yes,apple is in thistuple
5.建立有一個專案的元組
>>> thistuple = ("apple",) >>> print(type(thistuple)) <class 'tuple'> >>> thistuple = ("apple") >>> print(type(thistuple)) <class 'str'>
注:如需建立僅包含一個專案的元組,必須在該專案後新增一個逗號,否則 Python 無法將變數識別為元組
6.元組方法
方法 |
描述 |
返回元組中指定值出現的次數。 |
|
在元組中搜索指定的值並返回它被找到的位置。 |
三、集合
集合用花括號編寫
1. 建立集合
>>> thisset = {"apple", "banana", "cherry"} >>> print(thisset) {'apple', 'cherry', 'banana'}
2. 訪問專案
無法使用索引訪問set中的專案,因為set是無序的,沒有索引
可以使用for迴圈遍歷set專案,或者使用in關鍵字查詢集合中是否存在指定值
>>> for x in thisset: ... print(x) ... apple cherry banana >>> print("apple" in thisset) True
3. 更改專案
集合一旦建立,無法更改專案。但是可以新增新專案
要將一個專案新增到集合,使用add()方法
要向集合中新增多個專案,使用update()方法
>>> thisset.add("orange") >>> print(thisset) {'apple', 'cherry', 'banana', 'orange'} >>> thisset.update(["orange", "mango", "grapes"]) >>> print(thisset) {'banana', 'grapes', 'apple', 'cherry', 'orange', 'mango'}
4. 獲取set長度
使用len()方法確定set集合中有多少專案
>>> print(thisset) {'banana', 'grapes', 'apple', 'cherry', 'orange', 'mango'} >>> print(len(thisset)) 6
5. 刪除專案
使用remove()或discard(),pop()方法
>>> thisset = {"apple", "banana", "cherry"} >>> thisset.remove("banana") >>> print(thisset) {'apple', 'cherry'} >>> thisset = {"apple", "banana", "cherry"} >>> thisset.discard("apple") >>> print(thisset) {'cherry', 'banana'} >>> thisset = {"apple", "banana", "cherry"} >>> thisset.pop() 'apple' >>> print(thisset) {'cherry', 'banana'}
clear()清空集合
>>> thisset = {"apple", "banana", "cherry"} >>> thisset.clear() >>> print(thisset) set()
del徹底刪除集合
>>> del thisset >>> print(thisset) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'thisset' is not defined
6. 合併集合
使用union()方法返回包含兩個集合中所有專案,也可使用update()方法將一個集合中所有的專案插入到另一個集合中。
>>> set1 = {"a", "b" , "c"} >>> set2 = {1,2,3,4} >>> set3 = set1.union(set2) >>> print(set3) {'a', 'b', 1, 2, 3, 4, 'c'}
>>> set1 = {"a", "b" , "c"} >>> set2 = {1,2,3,4} >>> set1.update(set2) >>> print(set1) {'a', 'b', 1, 2, 3, 4, 'c'}
注:union() 和 update() 都將排除任何重複項
7. set()建構函式
使用set()建構函式建立集合
>>> thisset = set(("apple", "banana", "cherry")) >>> print(thisset) {'apple', 'cherry', 'banana'}
8. set方法
方法 |
描述 |
向集合新增元素。 |
|
刪除集合中的所有元素。 |
|
返回集合的副本。 |
|
返回包含兩個或更多集合之間差異的集合。 |
|
刪除此集合中也包含在另一個指定集合中的專案。 |
|
刪除指定專案。 |
|
返回為兩個其他集合的交集的集合。 |
|
刪除此集合中不存在於其他指定集合中的專案。 |
|
返回兩個集合是否有交集。 |
|
返回另一個集合是否包含此集合。 |
|
返回此集合是否包含另一個集合。 |
|
從集合中刪除一個元素。 |
|
刪除指定元素。 |
|
返回具有兩組集合的對稱差集的集合。 |
|
插入此集合和另一個集合的對稱差集。 |
|
union() |
返回包含集合並集的集合。 |
用此集合和其他集合的並集來更新集合。 |
四、字典
在python中,字典用花括號編寫,擁有鍵和值
1. 建立字典
>>> thisdict = {"brand": "Porsche", "model": "911","year": 1963} >>> print(thisdict) {'model': '911', 'brand': 'Porsche', 'year': 1963}
2. 訪問專案
通過引用其鍵名來訪問字典專案
get()方法也可以獲取特定的值
>>> x = thisdict["model"] >>> print(x) 911 >>> y = thisdict.get("year") >>> print(y) 1963
3. 更改值
通過引用其鍵名來更改特定項的值
>>> thisdict["year"] = 2019 >>> print(thisdict) {'model': '911', 'brand': 'Porsche', 'year': 2019}
4. 遍歷字典
用for迴圈遍歷字典
遍歷字典時,返回值為字典的鍵
可以使用value()函式返回字典的值
使用items()函式遍歷鍵和值
>>> print(thisdict) {'model': '911', 'brand': 'Porsche', 'year': 2019} >>> for x in thisdict: ... print(x) ... model brand year >>> for x in thisdict: ... print(thisdict[x]) ... 911 Porsche 2019 >>> for x in thisdict.values(): ... print(x) ... 911 Porsche 2019>>> for x,y in thisdict.items(): ... print(x,y) ... model 911 brand Porsche year 2019 >>> thisdict = {"brand": "Porsche", "model": "911","year": 1963} >>> if "model" in thisdict: ... print("yes,'model' is one of the keys in the thisdict dictionary") ... else: ... print("no") ... yes,'model' is one of the keys in the thisdict dictionary
5. 新增專案
通過使用新的索引鍵併為其賦值,可以將專案新增到字典
>>> thisdict = {"brand": "Porsche", "model": "911","year": 1963} >>> thisdict["color"]="red" >>> print(thisdict) {'model': '911', 'color': 'red', 'brand': 'Porsche', 'year': 1963}
6. 刪除專案
pop()方法刪除具有指定鍵名的項
popitem()方法刪除
del關鍵字刪除具有指定鍵名的專案
del關鍵字也可以完全刪除字典
clear()清空字典
>>> thisdict = {'model': '911', 'color': 'red', 'brand': 'Porsche', 'year': 1963} >>> thisdict.pop("model") '911' >>> print(thisdict) {'color': 'red', 'brand': 'Porsche', 'year': 1963} >>> thisdict = {'model': '911', 'color': 'red', 'brand': 'Porsche', 'year': 1963} >>> thisdict.popitem() ('model', '911') >>> print(thisdict) {'color': 'red', 'brand': 'Porsche', 'year': 1963} >>> del thisdict["color"] >>> print(thisdict) {'brand': 'Porsche', 'year': 1963} >>> del thisdict >>> print(thisdict) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'thisdict' is not defined >>> thisdict = {'model': '911', 'color': 'red', 'brand': 'Porsche', 'year': 1963} >>> thisdict.clear() >>> print(thisdict) {}
7. 複製字典
使用copy()方法
使用dict()方法建立字典副本
>>> thisdict = {'model': '911', 'color': 'red', 'brand': 'Porsche', 'year': 1963} >>> mydict = thisdict.copy() >>> print(mydict) {'model': '911', 'color': 'red', 'brand': 'Porsche', 'year': 1963} >>> thisdict = {"brand": "Porsche", "model": "911","year": 1963} >>> mydict = dict(thisdict) >>> print(mydict) {'model': '911', 'brand': 'Porsche', 'year': 1963}
8. 巢狀字典
字典也可以包含很多字典
>>> myfamily = { "child1" : { "name" : "Phoebe Adele", "year" : 2002 }, "child2" : { "name" : "Jennifer Katharine", "year" : 1996 }, "child3" : { "name" : "Rory John", "year" : 1999 } }... ... ... ... ... ... ... ... ... ... ... ... ... >>> print(myfamily) {'child3': {'name': 'Rory John', 'year': 1999}, 'child1': {'name': 'Phoebe Adele', 'year': 2002}, 'child2': {'name': 'Jennifer Katharine', 'year': 1996}}
child1 = { "name" : "Phoebe Adele", "year" : 2002 } child2 = { "name" : "Jennifer Katharine", "year" : 1996 } child3 = { "name" : "Rory John", "year" : 1999 } myfamily = { "child1" : child1, "child2" : child2, "child3" : child3 }... ... ... >>> ... ... ... >>> ... ... ... >>> >>> ... ... ... ... >>> print(myfamily) {'child3': {'name': 'Rory John', 'year': 1999}, 'child1': {'name': 'Phoebe Adele', 'year': 2002}, 'child2': {'name': 'Jennifer Katharine', 'year': 1996}}
9. 字典方法
方法 |
描述 |
刪除字典中的所有元素 |
|
返回字典的副本 |
|
返回擁有指定鍵和值的字典 |
|
返回指定鍵的值 |
|
返回包含每個鍵值對的元組的列表 |
|
返回包含字典鍵的列表 |
|
刪除擁有指定鍵的元素 |
|
刪除最後插入的鍵值對 |
|
返回指定鍵的值。如果該鍵不存在,則插入具有指定值的鍵。 |
|
使用指定的鍵值對字典進行更新 |
|
返回字典中所有值的列表 |