從零開始學Python(第四天)


在這裏插入圖片描述

第四天

容器(collection)

​ python 中爲了方便一部分相似數據的處理,提供了各種組合類型,常見的如列表、元組、字典等組合數據類型。

【初識容器】

什麼是容器:
容器就是一種數據類型,複合數據類型,存儲多個變量;容器就是對象,對象都是存儲在堆中的;Python中萬物皆對象

在這裏插入圖片描述

Data area:數據區 靜態的不變的值

Code area:代碼區

Stack棧:申請變量 先進後出FILO 後進先出OIFO 棧的空間很小

LIFO:last in first out
FIFO:firt in first out 

Heap 堆:容器其實就是對象,對象是存儲在堆中的 堆的空間很大

【初知容器】

list 列表

1、可以存放多個數據

2、可以有重複的數據

3、數據是有序的 底層是基於雙向鏈表實現的

set 集合

1、可存放多個數據

2、不能存放重複的數據

3、存放的數據是無序的

tuple 元組

1、可以存放多個數據

2、可以存放重複的數據

3、存放的數據是有序的

4、存放的數據是固定的,不能發生變化的

dict 字典
1、存放的是key:value鍵值對數據

2、key是不能重複的,vlaue可以重複

3、存放的數據沒有順序

4.1 list列表

列表是一種線性表,線性表是有順序的表,因爲有序,所以有下標;且可以存儲相同的數據

線性表的實現:數組(array)、鏈表(list)、棧(stack)、隊列(queue),python中沒有數組

4.1.1 列表的定義

​ 1、藉助若數據類型語言的特點:直接賦值

>>> ls = [1,2,3,4,5]
>>> ls
[1, 2, 3, 4, 5]
>>> type(ls)
<class 'list'>
>>>
#可以嵌套使用,因爲列表本身也是對象
>>> username_age = [["Eichi","20"],["yichen","22"],["tongyichen","23"]]
>>> username_age
[['Eichi', '20'], ['yichen', '22'], ['tongyichen', '23']]
>>>

#列表的查看,根據下標 學過C、C++的同學可以理解爲數組,但又不太一樣,要注意區別
#超出列表的下標範圍,則會提示越界
>>> username_age[0]
['Eichi', '20']
>>> username_age[1]
['yichen', '22']
>>> username_age[2]
['tongyichen', '23']
>>> username_age[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
#多級訪問到嵌套的內部,請一定掌握,因爲遍歷列表時會反覆用到
>>> username_age[1][1]
'22'
>>> username_age[2][0]
'tongyichen'

​ 2、全局函數list

#查看list()函數的幫助文檔
>>> help(list)
Help on class list in module builtins:

class list(object)
 |  list(iterable=(), /)
 |
 |  Built-in mutable sequence.
 |
 |  If no argument is given, the constructor creates a new empty list.
 |  The argument must be an iterable if specified.
 
翻譯一下:
模塊內置中的類列表幫助:
類列表(對象)
|列表(iterable=,/|內置可變序列。
|如果沒有給出參數,則構造函數將創建一個新的空列表。
|如果指定了參數,則該參數必須是iterable。 

#全局函數list()的使用
>>> ls = list([1,2,3,4,5])
>>> ls
[1, 2, 3, 4, 5]
>>> 

4.1.2 列表的元素

1、element 容器中存儲的值
列表中元素如何訪問或者修改
可以利用下標來訪問元素或者修改元素
ls[下標] 下標從0開始

#上面已經簡單展示了通過下標來查看列表的某個元素,也可通過下標來修改列表的某個元素,注意,這是嵌套的列表,與二維數組不太一樣,但有相同點,不要搞混淆了
>>> username_age[2][0]
'tongyichen'
>>> username_age[2][0] = "haha"
>>> username_age[2][0]
'haha'
#無嵌套列表的下標訪問
>>> user = ["haha","xixi","hehe"]
>>> user
['haha', 'xixi', 'hehe']
>>> user[0]
'haha'
>>> user[1]
'xixi'
>>> user[2]
'hehe'
>>> user[0] = "heihei"
>>> user[0]
'heihei'
>>> user
['heihei', 'xixi', 'hehe']
>>>

2、獲取list中元素的個數
​ len的全局函數 可以接收可迭代對象
​ len(ls) # 獲取元素的個數

>>> user
['heihei', 'xixi', 'hehe']
>>> len(user)
3

4.1.3 列表的遍歷

​ for循環就是用於迭代可迭代對象的
​ while循環,需要一個索引,從0開始

#for循環後需要的就是一個可迭代對象,所以,直接寫user是完全正確的
>>> user
['heihei', 'xixi', 'hehe']
>>> for i in user:
...     print(i)
...
heihei
xixi
hehe

4.1.4 列表的常見方法

​ [‘append’, ‘clear’, ‘copy’, ‘count’, ‘extend’, ‘index’, ‘insert’,‘pop’, ‘remove’, ‘reverse’, ‘sort’]

|-- append(item)		# 將元素追加到list的末尾位置
|-- clear()				# 清空列表
|-- copy()				# 複製對象(淺拷貝對象)
|-- count(item)			# 統計元素在列表中出現的次數
|-- extend(list)		# 將一個列表合併到另外一個列表中
|-- index(item)			# 查找元素在列表中的第一個索引位置,如果不存在,則拋出異常
|-- insert(index, item)	# 插入元素,第一個參數是位置
|-- pop([index])		# 根據索引移除元素,如果沒有索引,默認移除最後一個
|-- remove(元素)		   # 根據值移除元素
|-- reverse				# 翻轉元素的順序
|-- sort				# 排序,只能同類型比較 如果是數字,就按照大小進行比較,如果是字符串,是按照ASCII表比較的
#常用方法的簡單演示,詳細的使用在習題中會詳細說明
>>> user.append("lala")
>>> user
['heihei', 'xixi', 'hehe', 'lala']
>>> user.insert(0,"eichi")
>>> user
['eichi', 'heihei', 'xixi', 'hehe', 'lala']
>>> user.pop()
'lala'
>>> user
['eichi', 'heihei', 'xixi', 'hehe']
>>> user.pop(0)
'eichi'
>>> user
['heihei', 'xixi', 'hehe']
>>> newuser = user.copy()
>>> newuser
['heihei', 'xixi', 'hehe']
>>> user.count("e")
0
>>> user.count("hehe")
1
>>> lis = [1,2,3,4,5]
>>> lis
[1, 2, 3, 4, 5]
>>> user
['heihei', 'xixi', 'hehe']
>>> lis.extend(user)
>>> lis
[1, 2, 3, 4, 5, 'heihei', 'xixi', 'hehe']
>>> lis.clear()
>>> lis
[]
>>> user
['heihei', 'xixi', 'hehe']
>>> user.index("hehe")
2
>>> user.index("heihei")
0
>>> user.index("haha")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'haha' is not in list
>>> user
['heihei', 'xixi', 'hehe']
>>> user.remove("hehe")
>>> user
['heihei', 'xixi']

全局函數:

len(list)可以獲取列表中數據的數量

max(list) 可以獲得列表中最大的數據

min(list) 可以獲得列表中最小的數據

list(seq) 將一個序列數據轉換成列表

>>> ls = [1,2,3,4,5]
>>> len(ls)
5
>>> max(ls)
5
>>> min(ls)
1
>>> lis = list([1,2,3])
>>> lis
[1, 2, 3]
>>>

4.2 set 集合

Set:無序的、不能重複的 ,因爲不能存儲相同的數據,所以無下下標

4.2.1 定義集合

​ s = {必須有元素}
​ s = set() 全局函數

#使用幫助文檔查看全局函數
Help on class set in module builtins:

class set(object)
 |  set() -> new empty set object
 |  set(iterable) -> new set object
 |
 |  Build an unordered collection of unique elements.
#翻譯一下
關於模塊內置中的類集的幫助:
類集(對象)
|set()->新建空set對象
|set(iterable)->新建set對象
|建立獨特元素的無序集合。
#因爲集合無序,所以不能通過下標來進行訪問
>>> name = {"eichi","yichen","chenyi"}
>>> name
{'yichen', 'chenyi', 'eichi'}
>>> name[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object is not subscriptable

4.2.2 常見方法

​ add’, ‘clear’, ‘copy’, ‘difference’, ‘difference_update’, ‘discard’,
​ ‘intersection’, ‘intersection_update’, ‘isdisjoint’, ‘issubset’, ‘issuperset’,
​ ‘pop’, ‘remove’, ‘symmetric_difference’, ‘symmetric_difference_update’, ‘union’,
​ ‘update’]

|-- add(item)		# 添加元素
|-- clear			# 清空集合
|-- copy(set)  		# 複製對象(淺拷貝對象)
|-- pop()			# 隨機移除元素
|-- remove(item)	# 刪除集合元素 
|-- discard			# 嘗試着移除元素 如果元素是成員,則將其從集合中移除。如果元素不是成員,則不執行任何操作。
|-- intersection	# 交集
|-- difference		# 差集
|-- union			# 並集
#常用方法的簡單演示,詳細的使用在習題中會詳細說明
>>> name = {"eichi","yichen","yichentong"}
>>> name
{'yichen', 'eichi', 'yichentong'}
>>> name.add("haha")
>>> name
{'yichen', 'haha', 'eichi', 'yichentong'}
>>> name.add(123)
>>> name
{'yichen', 'eichi', 'yichentong', 'haha', 123}
>>> user = name.copy()
>>> user
{'yichen', 'yichentong', 123, 'haha', 'eichi'}
>>> user.pop()
'yichentong'
>>> user.pop()
'yichen'
>>> user
{123, 'haha', 'eichi'}
>>> user.remove("eichi")
>>> user
{123, 'haha'}
>>> user
{123, 'haha'}
>>> user.discard(123)
>>> user
{'haha'}
>>> user
{'haha'}
>>> name
{'yichen', 'eichi', 'yichentong', 'haha', 123}
>>> name.intersection(user)
{'haha'}
>>> name.difference(user)
{'yichen', 123, 'eichi', 'yichentong'}
>>> name.union(user)
{'yichen', 'yichentong', 123, 'haha', 'eichi'}

4.2.3 集合的遍歷

>>> set = {"eichi","yichen","yichentong"}
>>> for i in set:
...     print(i)
...
eichi
yichen
yichentong

4.3 tuple 元組

()包裹的,特點是固定,不能發生變化的,是不可變類型,有序的(可以通過下標來進行訪問);可以理解爲列表的特殊形式,一旦生命就不允許改變

4.3.1 元組定義

t = (1,3,4,4,5)
tt = tuple((1,3,4,4,5))
#全局函數的解釋
Help on class tuple in module builtins:

class tuple(object)
 |  tuple(iterable=(), /)
 |
 |  Built-in immutable sequence.
 |
 |  If no argument is given, the constructor returns an empty tuple.
 |  If iterable is specified the tuple is initialized from iterable's items.
 |
 |  If the argument is a tuple, the return value is the same object.
 |

#翻譯一下
有關模塊內置中的類元組的幫助:
類元組(對象)
|元組(iterable=,/|內置不可變序列。
|如果沒有給出參數,則構造函數返回一個空元組。
|如果指定了iterable,則元組將從iterable的項初始化。
|如果參數是元組,則返回值是相同的對象。

4.3.2 元組的元素

count() 統計某個值的個數
index() 查看某個值的位置 如存在多個元素,默認查詢第一次出現的元素

#舉例
>>> t = tuple((1,2,3,4,55,5,4,4,3,2))
>>> t
(1, 2, 3, 4, 55, 5, 4, 4, 3, 2)
>>> t.count(4)
3
>>> t.count(3)
2
>>> t.count(100)
0
>>> t.count(100)
0
>>> t.index(55)
4
>>> t.index(4)
3
>>>

4.3.3 元組的注意事項

元組是不可變類型,也就意味着一旦元組創建,元素的個數、值都將固定,不能修改、刪除等操作;這是爲了代碼的安全性,所以在程序設計開發過程中,對於一部分不需要更改的數據可以定義成元組類型;元組類型的數據類似於C中的枚舉類型

如果子元素是可變類型,那就可以改變着個子元素。

例如:

>>> group = ("haha","xixi",["hehe","lala"])
>>> group
('haha', 'xixi', ['hehe', 'lala'])
>>> group[2][0]
'hehe'
>>> group[2][0] = "huhu"
>>> group[2][0]
'huhu'
>>> group[2][1]
'lala'
>>> group[2][1] = "aa"
>>> group[2][1]
'aa'
>>>
>>> group[0]
'haha'
>>> group[0] = "kk"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

面試題:

當元組中只存在一個元素時,類型就不是tuple
>>> t = (10)
>>> type(t)
<class 'int'>
>>> t=(10,)
>>> type(t)
<class 'tuple'>

4.3.4 元組的遍歷

與列表、集合類似,採用for循環來進行遍歷

>>> t
(1, 2, 3, 4, 55, 5, 4, 4, 3, 2)
>>> for i in t:
...     print(i)
...
1
2
3
4
55
5
4
4
3
2

4.4 dict 字典

字典是一種鍵值對形式存儲的數據結構,鍵是唯一的,在python中鍵只能存儲字符串類型

4.4.1 字典的定義

語法結構:

字典變量名稱={“變量 1”:”值 1”, “變量 2”:”值 2”, “變量 3”:”值 3”,}

定義的時候以鍵值對的形式定義存在,相當於給每個值取了名字

舉例:

>>> d = {"name":"eichi","age":20,"address":"xian"}
>>> d
{'name': 'eichi', 'age': 20, 'address': 'xian'}
>>> di = dict({"name":"eichi","age":20,"address":"xian"})
>>> di
{'name': 'eichi', 'age': 20, 'address': 'xian'}

#訪問查詢
>>> d["name"]
'eichi'
>>> d["age"]
20
>>> d["address"]
'xian'

全局函數的解釋:

>>> help(dict)
Help on class dict in module builtins:

class dict(object)
 |  dict() -> new empty dictionary
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v
 |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
 |      in the keyword argument list.  For example:  dict(one=1, two=2)
 
 #翻譯一下
>>>幫助(dict)
關於模塊內置中的類dict的幫助:
類dict(對象)
|dict()->新建空字典
|dict(映射)->從映射對象的
|(鍵,值)對
|dict(iterable)->新字典初始化爲通過:
|d={}
|對於iterable中的k,v:
|d[k]=v
|dict(**kwargs)->用name=value對初始化的新字典
|在關鍵字參數列表中。例如:dict(one=1,two=2) 

4.4.2 字典的常用方法

常見方法:
'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop',
'popitem', 'setdefault', 'update', 'values']
|-- clear()			#清空字典
|-- copy(dict)		#複製對象(淺拷貝對象)
|-- get(key,default)#用於返回鍵對應的值,參數寫的是鍵,第二個參數,用於給一個默認值,返回的是默認值
|-- keys()			#返回鍵
|-- values()		#返回值
|-- items()     	#返回的是元組
|-- pop(key)		# 通過key,移除對應的鍵值對
|-- popitem			# LIFO的順序
					LIFO:last in first out 後進先出
					FIFO:firt in first out python無隊列 先進先出
>>> d
{'name': 'eichi', 'age': 20, 'address': 'xian'}
>>> dic = d.copy()
>>> dic
{'name': 'eichi', 'age': 20, 'address': 'xian'}
>>> dic.clear()
>>> dic
{}
>>> d.get("name")
'eichi'
#由於d中沒有name1這個key,所以使用get()函數查詢時,給的默認值是多少就是多少
>>> d.get("name1","chi") 
'chi'

>>> d
{'name': 'eichi', 'age': 20, 'address': 'xian'}
>>> d.keys()
dict_keys(['name', 'age', 'address'])
>>> d.values()
dict_values(['eichi', 20, 'xian'])
>>> d.items()
dict_items([('name', 'eichi'), ('age', 20), ('address', 'xian')])
>>> d.pop("name")
'eichi'
>>> d
{'age': 20, 'address': 'xian'}
>>>

4.4.3 字典的遍歷方式(三種)

>>> d = dict({"name":"eichi","age":"20","address":"xian"})
>>> d
{'name': 'eichi', 'age': '20', 'address': 'xian'}

#1
>>> for k in d:      #這裏實際上是d.keys() 即所有的鍵
...     print(k+"-->"+d.get(k))   #也可以這樣輸出print(k,d[k])
...
name-->eichi
age-->20
address-->xian

#2
>>> for k in d.keys():
...     print(k,d[k])
...
name eichi
age 20
address xian

#3
>>> for (k,v) in d.items():
...     print(k,v)
...
name eichi
age 20
address xian

4.5 比較

➢ 元組 Tuple 是存放固定的數據
➢ 集合 Set 中的數據插入和遍歷的時間,隨數據增多而變慢
➢ 列表 List 中的數據插入和查詢的時間,隨數據的增多而變慢
➢ 字典 Dict 中的數據插入和查詢的速度非常快,不會因爲數據太多而變慢
元組、集合和列表佔用內存較少,字典佔用內存較多,字典是一種通過佔用空間來換取
操作速度的一種數據類型。

今天的內容到這裏就結束了~ 需要做題鞏固練習的,請保持關注,持續更新中ing

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章