python里set有哪些成功案例

小樊
82
2024-08-11 08:49:41

  1. 去重操作:set最常見(jiàn)的用途就是去除列表或者其他序列中的重復(fù)元素,可以通過(guò)將序列轉(zhuǎn)換為set來(lái)去除重復(fù)元素。
lst = [1, 2, 2, 3, 4, 4, 5]
unique_set = set(lst)
print(unique_set)  # 輸出:{1, 2, 3, 4, 5}
  1. 集合運(yùn)算:set提供了豐富的集合運(yùn)算方法,比如并集、交集、差集等操作。
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
union_set = set1.union(set2)
intersection_set = set1.intersection(set2)
difference_set = set1.difference(set2)
print(union_set)  # 輸出:{1, 2, 3, 4, 5, 6, 7}
print(intersection_set)  # 輸出:{3, 4, 5}
print(difference_set)  # 輸出:{1, 2}
  1. 快速查找:set內(nèi)部是使用哈希表實(shí)現(xiàn)的,因此可以快速進(jìn)行成員檢查操作。
s = {1, 2, 3, 4, 5}
if 3 in s:
    print("3存在于集合中")
  1. 標(biāo)記重復(fù)元素:可以利用set的不可重復(fù)性質(zhì)來(lái)判斷是否存在重復(fù)元素。
lst = [1, 2, 2, 3, 4, 4, 5]
if len(lst) == len(set(lst)):
    print("列表中沒(méi)有重復(fù)元素")
else:
    print("列表中存在重復(fù)元素")
  1. 使用set進(jìn)行去重統(tǒng)計(jì):可以利用set和列表推導(dǎo)式來(lái)統(tǒng)計(jì)列表中不重復(fù)元素的個(gè)數(shù)。
lst = [1, 2, 2, 3, 4, 4, 5]
unique_elements_count = len({x for x in lst})
print(unique_elements_count)  # 輸出:5

0