Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

pythonset()函数

作者:寒江映月   发布日期:2026-05-02   浏览:124

# 示例代码:使用 Python 的 set() 函数

# 创建一个空的集合
empty_set = set()
print("创建一个空的集合:", empty_set)

# 从列表创建集合,自动去除重复元素
my_list = [1, 2, 2, 3, 4, 4, 5]
my_set = set(my_list)
print("从列表创建集合并去除重复元素:", my_set)

# 添加元素到集合
my_set.add(6)
print("添加元素到集合:", my_set)

# 移除集合中的元素
my_set.remove(3)  # 如果元素不存在会抛出 KeyError
print("移除集合中的元素:", my_set)

# 使用 discard 方法移除元素(不会抛出异常)
my_set.discard(7)  # 如果元素不存在也不会报错
print("使用 discard 方法移除元素:", my_set)

# 集合运算
set1 = {1, 2, 3}
set2 = {3, 4, 5}

union_set = set1.union(set2)  # 并集
print("两个集合的并集:", union_set)

intersection_set = set1.intersection(set2)  # 交集
print("两个集合的交集:", intersection_set)

difference_set = set1.difference(set2)  # 差集
print("两个集合的差集:", difference_set)

symmetric_difference_set = set1.symmetric_difference(set2)  # 对称差集
print("两个集合的对称差集:", symmetric_difference_set)

解释说明:

  • set() 函数用于创建一个新的集合。
  • 集合是一个无序且不重复的元素集合。
  • 可以通过 add() 方法向集合中添加元素。
  • 使用 remove()discard() 方法可以移除集合中的元素,区别在于 remove() 在元素不存在时会抛出异常,而 discard() 不会。
  • 集合支持常见的集合运算,如并集、交集、差集和对称差集。

上一篇:python闭包

下一篇:python 定义函数

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python的assert基本用法

python开发windows应用程序

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站