首页Python【Python内置函数】s...

【Python内置函数】set()函数

Python 提供了许多内置函数,这些函数是Python语言的一部分,可以直接在Python程序中使用而无需导入任何模块。

本系列将会陆续整理分享一些的Python内置函数。

文章配套代码获取有以下两种途径:
  • 通过百度网盘获取:
链接:https://pan.baidu.com/s/11x9_wCZ3yiYOe5nVcRk2CQ?pwd=mnsj 提取码:mnsj
  • 前往GitHub获取
https://github.com/returu/Python_built-in_functions





01
简介

set()函数用于创建一个集合(set)。集合是一个无序的、不重复的元素集合,它支持数学上的集合操作,如并集、交集、差集等。集合中的元素必须是可哈希(hashable)的,即不可变类型(如整数、浮点数、字符串、元组等)。

set() 函数的基本语法如下:

set(iterable)
参数说明:
  • iterable:一个可迭代对象(如列表、元组、字符串等)。如果没有提供参数,则创建一个空集合。

返回值:

set() 函数返回一个集合。

02
使用

下面是一些使用 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}

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

RELATED ARTICLES

欢迎留下您的宝贵建议

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments