本系列将会陆续整理分享一些的Python内置函数。
-
通过百度网盘获取:
链接:https://pan.baidu.com/s/11x9_wCZ3yiYOe5nVcRk2CQ?pwd=mnsj
提取码:mnsj
-
前往GitHub获取:
https://github.com/returu/Python_built-in_functions
set(iterable)
-
iterable:一个可迭代对象(如列表、元组、字符串等)。如果没有提供参数,则创建一个空集合。
返回值:
下面是一些使用 set() 函数的示例:
-
示例 1:基本使用
# 创建空集合
empty_set = set()
print(empty_set) # 输出:set()
# 从列表创建集合
my_list = [1, 2, 2, 3, 4, 4, 5]
my_set = set(my_list)
print(my_set) # 输出:{1, 2, 3, 4, 5},重复元素被自动去除
# 从字符串创建集合
my_string = "hello"
my_set = set(my_string)
print(my_set) # 输出:{'l', 'h', 'o', 'e'},重复字符被自动去除
# 从元组创建集合
my_tuple = (1, 2, 3, 4, 4)
my_set = set(my_tuple)
print(my_set) # 输出:{1, 2, 3, 4},重复元素被自动去除
-
示例 2:集合的操作
集支持多种操作方法以及集合运算。
# 添加元素:add() 方法
my_set = {1, 2, 3}
my_set.add(4) # 添加元素
my_set.update([5, 6]) # 批量添加
print(my_set) # 输出:{1, 2, 3, 4, 5, 6}
# 移除元素:remove() 或 discard() 方法
my_set = {1, 2, 3}
my_set.remove(2) # 如果元素不存在,会抛出 KeyError
my_set.discard(4) # 如果元素不存在,不会抛出错误
print(my_set) # 输出:{1, 3}
# 集合运算
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# 并集:union() 或 |
print(set1.union(set2)) # 输出:{1, 2, 3, 4, 5}
print(set1 | set2) # 输出:{1, 2, 3, 4, 5}
# 交集:intersection() 或 &
print(set1.intersection(set2)) # 输出:{3}
print(set1 & set2) # 输出:{3}
# 差集:difference() 或 -
print(set1.difference(set2)) # 输出:{1, 2}
print(set1 - set2) # 输出:{1, 2}
# 对称差集:symmetric_difference() 或 ^
print(set1.symmetric_difference(set2)) # 输出:{1, 2, 4, 5}
print(set1 ^ set2) # 输出:{1, 2, 4, 5}


本篇文章来源于微信公众号: 码农设计师