溫馨提示×

如何正確運用python的set函數(shù)

小樊
81
2024-09-08 22:09:09
欄目: 編程語言

Python 中的 set 是一個無序的不重復元素集合,可以使用大括號 {} 或者內(nèi)置函數(shù) set() 來創(chuàng)建。這里有一些關(guān)于如何正確使用 Python 的 set 函數(shù)的例子:

  1. 創(chuàng)建一個空集合
empty_set = set()
print(empty_set)  # 輸出:set()
  1. 從列表創(chuàng)建集合
my_list = [1, 2, 3, 4, 4, 5, 6, 6]
my_set = set(my_list)
print(my_set)  # 輸出:{1, 2, 3, 4, 5, 6}
  1. 添加元素到集合
my_set = {1, 2, 3}
my_set.add(4)
print(my_set)  # 輸出:{1, 2, 3, 4}
  1. 從集合中刪除元素
my_set = {1, 2, 3, 4}
my_set.remove(4)
print(my_set)  # 輸出:{1, 2, 3}
  1. 檢查元素是否在集合中
my_set = {1, 2, 3}
print(1 in my_set)  # 輸出:True
print(4 in my_set)  # 輸出:False
  1. 集合的交集、并集、差集和對稱差集
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

intersection = set_a.intersection(set_b)
print(intersection)  # 輸出:{3, 4}

union = set_a.union(set_b)
print(union)  # 輸出:{1, 2, 3, 4, 5, 6}

difference = set_a.difference(set_b)
print(difference)  # 輸出:{1, 2}

symmetric_difference = set_a.symmetric_difference(set_b)
print(symmetric_difference)  # 輸出:{1, 2, 5, 6}
  1. 將集合轉(zhuǎn)換為列表
my_set = {1, 2, 3, 4}
my_list = list(my_set)
print(my_list)  # 輸出:[1, 2, 3, 4]

通過上述示例,你應該已經(jīng)了解了如何在 Python 中正確地使用 set 函數(shù)。記住,集合是一個無序的數(shù)據(jù)結(jié)構(gòu),所以它們不能被索引或排序。如果你需要這些功能,請考慮使用列表或元組。

0