wordpress 手動(dòng)安裝seo怎么做教程
Python的基礎(chǔ)數(shù)據(jù)類型
- 數(shù)值類型:整數(shù)、浮點(diǎn)數(shù)、復(fù)數(shù)、布爾
- 字符串
- 容器類型:列表、元祖、字典、集合
集合
集合(set)是Python中一個(gè)非常強(qiáng)大的數(shù)據(jù)類型,它存儲(chǔ)的是一組無序且不重復(fù)的元素,集合中的元素必須是不可變的,且元素之間用逗號(hào)隔開,集合的元素之間用大括號(hào)括起來。集合是可變數(shù)據(jù)類型。
集合的特點(diǎn):
- 確定性:集合中的元素是不可變類型。集合是可變數(shù)據(jù)類型。
- 互異性:集合中的元素互不相同,不能重復(fù),元素是唯一的。
- 無序性:集合中的元素?zé)o序,即不能通過索引訪問集合中的元素。只能遍歷。
定義集合
可以使用大括號(hào) {} 或者 set() 函數(shù)來創(chuàng)建集合。如果使用大括號(hào),則至少需要包含一個(gè)元素;如果使用 set(),則可以創(chuàng)建一個(gè)空集合。
# 創(chuàng)建一個(gè)空集合
empty_set = set()
# 創(chuàng)建一個(gè)包含一個(gè)元素的集合
single_element_set = {1}
# 創(chuàng)建一個(gè)包含幾個(gè)元素的集合
my_set = {1, 2, 3, 'a', 'b', 'c'}
訪問集合元素
由于集合是無序的,因此不能通過索引來訪問元素。但是,可以使用循環(huán)來遍歷集合中的所有元素。
# 遍歷集合
for element in my_set:print(element)
集合操作
集合支持多種操作,如并集、交集、差集等。
- 并集(Union):使用 | 運(yùn)算符或 union() 方法。
- 交集(Intersection):使用 & 運(yùn)算符或 intersection() 方法。
- 差集(Difference):使用 - 運(yùn)算符或 difference() 方法。
- 對(duì)稱差集(Symmetric Difference):使用 ^ 運(yùn)算符或 symmetric_difference() 方法。
# 定義兩個(gè)集合
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}# 并集
union_set = set1 | set2 # 或 set1.union(set2)
union_set1 = set1.union(set2)
print(union_set)
print(union_set1)
# 交集
intersection_set = set1 & set2 # 或 set1.intersection(set2)
intersection_set1 = set1.intersection(set2)
print(intersection_set)
print(intersection_set1)
# 差集
difference_set = set1 - set2 # 或 set1.difference(set2)
difference_set1 = set1.difference(set2)
print(difference_set)
print(difference_set1)
# 對(duì)稱差集
symmetric_difference_set = set1 ^ set2 # 或 set1.symmetric_difference(set2)
symmetric_difference_set1 = set1.symmetric_difference(set2)
print(symmetric_difference_set)
print(symmetric_difference_set1)
集合方法
集合還提供了許多有用的方法,如:
- add():向集合中添加一個(gè)元素。
- remove():從集合中移除一個(gè)元素,如果元素不存在,則拋出 KeyError。
- discard():從集合中移除一個(gè)元素,如果元素不存在,則什么也不做。
- pop():隨機(jī)移除并返回集合中的一個(gè)元素。
- clear():清空集合中的所有元素。
# 向集合中添加元素
my_set.add('d')
print(my_set)# 從集合中移除元素
my_set.remove('a')
print(my_set)# 清空集合
my_set.clear()
print(my_set)
集合推導(dǎo)式
與列表推導(dǎo)式類似,集合推導(dǎo)式可以用來生成集合。
# 創(chuàng)建一個(gè)包含0-9每個(gè)數(shù)字的平方的集合
squared_set = {x**2 for x in range(10)}
print(squared_set)
# 列表推導(dǎo)式
s = {8, 3, 1, 5, 11}
{i * 2 for i in s}
集合在Python中是一種非常有用的數(shù)據(jù)類型,特別是在需要快速檢查元素是否存在或執(zhí)行集合運(yùn)算時(shí)。
附件
本文對(duì)應(yīng)的jupyter notebook源碼鏈接,歡迎下載練習(xí):https://download.csdn.net/download/fx_yzjy101/89760705
如有問題請(qǐng)留言。