目錄
0.三者主要作用
1.元組
元組特點
創建元組
元組解包
可變和不可變元素元組
2.集合
集合特點
創建集合
集合元素要求
集合方法
訪問與修改
子集和超集
相等性判斷
集合運算
不可變集合
3.字典
字典特點
字典創建和常見操作
字典內置方法
pprin模塊
0.三者主要作用
1.元組
元組特點
創建元組
# 創建一個空元組
t1 = ()
t2 = tuple()# 創建一個具有 3 個元素的元組
t3 = (1, 2, 3)# 使用 tuple 函數通過列表創建一個元組
t4 = tuple([x for x in range(5)])# 使用 tuple 函數通過字符串創建一個元組
t5 = tuple("abcdabcd")
# t5 = ('a', 'b', 'c', 'd', 'a', 'b', 'c', 'd')# 使用 list 函數將元組轉換為列表
t6 = list(t5)
# t6 = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']
創建只有一個元素的元組
# 創建一個只有一個元素的元組
t1 = (4,) # 注意有個逗號
t1 = 4, # 元組
t2 = (1) # t2 不是元組,而是一次賦值,將 1 賦給 t2
print(type(t2), t2) # <class 'int'> 1
元組解包
在Python中,元組解包是一種將元組中的多個值賦給多個變量的方式。這可以在賦值操作中直接完成,也可以在函數調用中使用來提供參數。
解包可以使用星號表達式來選擇性地解包元組中的部分元素。
# -*- coding: utf-8 -*-# 直接解包
tup = (1, 2, 3)
a, b, c = tup
print(a, b, c)
# a = 1, b = 2, c = 3# 使用星號表達式解包
tup = (1, 2, 3, 4, 5)
x, y, *rest = tup
print(x, y, rest)
# x = 1, y = 2, rest = [3, 4, 5]# 函數調用中的解包
def func(v1, v2, v3):print(v1, v2, v3)args = (1, 2, 3)
# func(args)
# TypeError: func() missing 2 required positional arguments: 'v2' and 'v3'
func(*args) # 輸出: 1 2 3# 函數返回多個值時的解包
def get_values():return 1, 2, 3a, b, c = get_values() # a = 1, b = 2, c = 3
可變和不可變元素元組
一個元組包含了一個固定的元素列表。一個元組里的一個個體元素可能是易變的。如果一個元組的元素都是不可變的,那么這個元組被稱為元素不可變元組。否則是元素可變元組。
# -*- coding: utf-8 -*-# 元素不可變元組
data = (1, 2, 3) # 這里1, 2, 3都是不可變的
data2 = ("abc", "hello", "world") # 這里字符串"abc", "hello", "world"都是不可變的
# data2[0][0] = 'x'
# 將會報錯:TypeError: 'str' object does not support item assignment# 元素可變元組
data3 = ([1, 2, 3], ["x", "y"]) # [1, 2, 3]是列表,是可變的
data3[0][0] = 100 # 不會報錯
print(data3) # ([100, 2, 3], ['x', 'y'])
# 這里是將元組的第一個元素,是個列表,這個列表的第一個元素的地址進行改變
# 而沒有該彼岸元組第一個元素的地址,即還是這個列表# 元組本身不可變和可變是指在元組內容初始化后,不能更改元組元素的內存地址
value = [99, 99]
# data3[0] = value
# 將會報錯:TypeError: 'tuple' object does not support item assignment
# 這里試圖將data3這個元組的第一個元素的地址換成[99, 99]的地址,是非法的
# 因為元組是不可變的
2.集合
集合特點
創建集合
# -*- coding: utf-8 -*-# 創建一個空集
set1 = set() # 注意 set2 = {} 是創建了一個字典# 創建 1 個元素的集合
set2 = {5}# 創建 3 個元素的集合
set3 = {1, 3, 5}# 用 set 函數通過元組創建集合
set4 = set((1, 3, 5))# 用 set 函數通過列表創建集合
set5 = set([x ** 2 for x in range(5)])# 用 set 函數通過字符串創建集合
set6 = set("helloworld")
print(set6) # 注意集合是無序的,每次打印可能會不一樣# 用 list 函數通過集合創建一個列表
list1 = list(set5)# 用 tuple 函數通過集合創建一個元組
t1 = tuple(set5)
集合元素要求
# -*- coding: utf-8 -*-set1 = {1, 3, 5} # ok
set2 = {[1, 2], [3]} # error:TypeError: unhashable type: 'list'
集合方法
訪問與修改
# -*- coding: utf-8 -*-set1 = {1, 2, 3, "a", "b"}
# 對集合添加一個元素
set1.add(4)
print(set1)# update 方法 # 單個元素用 add,可迭代的對象用 update
set1 = {1, 2, 3}
set1.update("abc")
print(set1) # {1, 2, 3, 'b', 'c', 'a'}
set1.update({2, 3, 4})
print(set1) # {1, 2, 3, 'b', 'c', 4, 'a'}
set1.update([4, 5, 6])
print(set1) # {1, 2, 3, 'b', 'c', 4, 5, 6, 'a'}# 刪除元素
set1.remove(3) # 刪除元素,不存在則拋出一個 KeyError 異常
print(set1.pop())
set1.discard(3) # 刪除元素,不存在不報錯# len 函數、max 函數、min 函數、sum 函數
print(len(set1))# 可以使用 for 循環遍歷一個集合中的所有元素
for x in set1:print(x)# in 和 not in
print(100 in set1)
子集和超集
set1 = {1, 2, 3}
set2 = {1, 3, 2, 4}
print(set1.issubset(set2)) # True
print(set2.issuperset(set1)) # True
比較運算符
相等性判斷
set1 = {1, 2, 3}
set2 = {1, 3, 2, 4}
set3 = {3, 1, 2,2}
print(set1 == set2) # False
print(set1 != set2) # True
print(set1 == set3) # True
集合運算
set1 = {1, 2, 4}
set2 = {1, 3, 5}
print(set1.union(set2)) # {1, 2, 3, 4, 5}
print(set1 | set2) # {1, 2, 3, 4, 5}
print(set1.intersection(set2))
print(set1 & set2) # {1}
print(set1.difference(set2))
print(set1 - set2) # {2, 4}
print(set1.symmetric_difference(set2))
print(set1 ^ set2) # {2, 3, 4, 5}
不可變集合
# -*- coding: utf-8 -*-# 可變集合
set1 = {1, 2, 3, "a", "b"}
set1.add(4) # ok
print(set1) # {1, 2, 3, 4, 'b', 'a'}# 不可變集合
data = [1, 2, 3]
set2 = frozenset(data) # 轉變為不可變集合
# set2.add(4) # AttributeError: 'frozenset' object has no attribute 'add'
3.字典
字典特點

字典創建和常見操作
# 創建空字典
d0 = {}# 創建具有 3 個條目的字典
d1 = {11: "bob", 12: "other", "ras2": 234}
print(type(d1)) # <class 'dict'>
print(d1) # {11: 'bob', 12: 'other', 'ras2': 234}
在Python中創建字典時,通常不需要顯式指定鍵(key)和值(value)的類型,因為字典是一種動態類型的數據結構,它可以容納任意類型的鍵和值。然而,如果你想在字典中指定鍵和值的類型,可以使用類型提示(Type Hints)來提供額外的信息,這在代碼的可讀性和維護性方面是有益的。
# -*- coding: utf-8 -*-from typing import Dict, Any, Union# 使用類型提示聲明字典的鍵和值的類型
my_dict: Dict[str, Union[int, str]] = {"key1": 42,"key2": "value2","key3": 3.14 # 這個值將被視為 Union[int, str] 中的任一類型
}# 打印字典
print(my_dict)
請注意,類型提示僅僅是一種靜態分析工具,對于 Python 解釋器本身并沒有強制約束。它主要用于提高代碼的可讀性和與其他開發者的交流。
# -*- coding: utf-8 -*-# 添加一個條目到字典中,dictionaryName[key] = value
d1 = {"22-23-1827": "bob"}d1["22-23-1828"] = "tom"
print(d1) # {'22-23-1827': 'bob', '22-23-1828': 'tom'}# 如果這個關鍵字在字典中已經存在,添加條目的語法將替換該關鍵字對應的值
d1["22-23-1828"] = "xxxxx"
print(d1) # {'22-23-1827': 'bob', '22-23-1828': 'xxxxx'}# 從字典中獲取一個值,varName = dictionaryName[key]
x = d1["22-23-1827"]
print(x)# 如果字典中沒有這個關鍵字,將拋出一個 KeyError 異常
# print(d1["123456"]) # KeyError: '123456'
d2 = {'22-23-1827': 'tom', '22-23-1828': 'bob'}
del d2['22-23-1828']
print(d2) # {'22-23-1827': 'tom'}# 如果字典中沒有這個關鍵字,將拋出一個 KeyError 異常
d2 = {'22-23-1827': 'tom', '22-23-1828': 'bob'}
for key in d2:print(key + " : " + d2[key])
"""
22-23-1827 : tom
22-23-1828 : bob
"""
d2 = {'22-23-1827': 'tom', '22-23-1828': 'bob'}
print(len(d2)) # 2
d2 = {'22-23-1827': 'tom', '22-23-1828': 'bob'}
print('22-23-1827' in d2) # True
print('123456' in d2) # False
print('tom' in d2) # False
d1 = {'22-23-1827': 'tom', '22-23-1828': 'bob'}
d2 = {'22-23-1828': 'bob', '22-23-1827': 'tom'}
print(d1 == d2) # True
print(d2 != d1) # False
字典內置方法

data = {'tom': 18, 'bob': 19}
print(data.get('tom')) # 18
print(data.get('zhang')) # None
print(data.get('zhang', 99)) # 99
data = {'tom': 18, 'bob': 19}print(data.setdefault('tom', 100)) # 18
print(data) # {'tom': 18, 'bob': 19}print(data.setdefault('zhang', 100)) # 100
print(data) # {'tom': 18, 'bob': 19, 'zhang': 100}print(data.setdefault('zhang', 999)) # 100
print(data) # {'tom': 18, 'bob': 19, 'zhang': 100}
data = {'tom': 18, 'bob': 19}ret = data.pop("tom")
print(data) # {'bob': 19}
print(ret) # 18# data.pop("xxx") # KeyError: 'xxx'ret = data.pop("xxx", 100) # 不會KeyError
print(data) # {'bob': 19}
print(ret) # 100
update 方法用來字典合并
# 相同 key 的部分新的字典會覆蓋舊的字典
old_dict = {"部門": "財務", "姓名": "王濤", "電話": 12345678900}
new_dict = {"性別": "男", "部門": "技術", "電話": 12734735335}
old_dict.update(new_dict)
print(old_dict) # {'部門': '技術', '姓名': '王濤', '電話': 12734735335, '性別': '男'}
keys()、values()和items()方法
data = {'tom': 18, 'bob': 19}x1 = data.keys()
y1 = tuple(x1)
print(x1) # dict_keys(['tom', 'bob'])
print(y1) # ('tom', 'bob')
print()x2 = data.values()
y2 = list(x2)
print(x2) # dict_values([18, 19])
print(y2) # [18, 19]
print()x3 = data.items()
y3 = tuple(x3)
print(x3) # dict_items([('tom', 18), ('bob', 19)])
print(y3) # (('tom', 18), ('bob', 19))
print()
pprin模塊
# -*- coding: utf-8 -*-import pprintmessage = "我愛程序設計,我要好好學習,天天向上。"
count_dict = {}
for character in message:count_dict[character] = count_dict.get(character, 0) + 1#print(count_dict)
#print()pprint.pprint(count_dict)
print()new = pprint.pformat(count_dict)
print(new)
print()
運行結果
{'。': 1,'上': 1,'習': 1,'向': 1,'天': 2,'好': 2,'學': 1,'序': 1,'我': 2,'愛': 1,'程': 1,'要': 1,'計': 1,'設': 1,',': 2}{'。': 1,'上': 1,'習': 1,'向': 1,'天': 2,'好': 2,'學': 1,'序': 1,'我': 2,'愛': 1,'程': 1,'要': 1,'計': 1,'設': 1,',': 2}
end