溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

Python編程小技巧:set函數(shù)的應(yīng)用實(shí)例

發(fā)布時(shí)間:2024-10-06 09:15:04 來(lái)源:億速云 閱讀:81 作者:小樊 欄目:編程語(yǔ)言

Python中的set函數(shù)是一個(gè)無(wú)序且不重復(fù)的數(shù)據(jù)集合,它支持?jǐn)?shù)學(xué)集合運(yùn)算,如并集、交集、差集和對(duì)稱(chēng)差集等。以下是一些set函數(shù)的應(yīng)用實(shí)例:

  1. 創(chuàng)建一個(gè)set集合:
s = set([1, 2, 3, 4, 5])
print(s)  # 輸出:{1, 2, 3, 4, 5}
  1. 使用add()方法向set集合中添加元素:
s = set([1, 2, 3])
s.add(4)
print(s)  # 輸出:{1, 2, 3, 4}
  1. 使用update()方法向set集合中添加多個(gè)元素:
s = set([1, 2, 3])
s.update([4, 5, 6])
print(s)  # 輸出:{1, 2, 3, 4, 5, 6}
  1. 使用remove()方法從set集合中刪除指定元素:
s = set([1, 2, 3, 4, 5])
s.remove(3)
print(s)  # 輸出:{1, 2, 4, 5}
  1. 使用pop()方法從set集合中隨機(jī)刪除并返回指定元素:
s = set([1, 2, 3, 4, 5])
popped_element = s.pop()
print(popped_element)  # 輸出:隨機(jī)返回1-5之間的整數(shù)
print(s)  # 輸出:剩余元素的集合
  1. 使用len()函數(shù)獲取set集合的長(zhǎng)度:
s = set([1, 2, 3, 4, 5])
print(len(s))  # 輸出:5
  1. 使用in關(guān)鍵字判斷元素是否在set集合中:
s = set([1, 2, 3, 4, 5])
print(3 in s)  # 輸出:True
print(6 in s)  # 輸出:False
  1. 使用set()函數(shù)計(jì)算兩個(gè)集合的并集、交集、差集和對(duì)稱(chēng)差集:
s1 = set([1, 2, 3, 4])
s2 = set([3, 4, 5, 6])

union_set = s1.union(s2)  # 并集
print(union_set)  # 輸出:{1, 2, 3, 4, 5, 6}

intersection_set = s1.intersection(s2)  # 交集
print(intersection_set)  # 輸出:{3, 4}

difference_set = s1.difference(s2)  # 差集
print(difference_set)  # 輸出:{1, 2}

symmetric_difference_set = s1.symmetric_difference(s2)  # 對(duì)稱(chēng)差集
print(symmetric_difference_set)  # 輸出:{1, 2, 5, 6}
向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI