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

set函数在python中的用法

作者:残缺的不完美   发布日期:2025-06-21   浏览:22

# 示例代码:set函数在Python中的用法

# 创建一个集合
my_set = set([1, 2, 3, 4, 5])
print("创建的集合:", my_set)

# 使用set()去重
repeated_list = [1, 2, 2, 3, 4, 4, 5]
unique_set = set(repeated_list)
print("去重后的集合:", unique_set)

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

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

# 集合的交集操作
set1 = set([1, 2, 3, 4])
set2 = set([3, 4, 5, 6])
intersection = set1.intersection(set2)
print("集合的交集:", intersection)

# 集合的并集操作
union = set1.union(set2)
print("集合的并集:", union)

# 集合的差集操作
difference = set1.difference(set2)
print("集合的差集:", difference)

解释说明:

  • set() 函数用于创建一个集合,集合是无序且不重复的元素集合。
  • 可以通过 set() 函数将列表转换为集合来去除重复元素。
  • 使用 add() 方法可以向集合中添加元素。
  • 使用 remove() 方法可以从集合中移除指定元素(如果元素不存在会抛出异常)。
  • 集合支持常见的集合操作如交集、并集和差集等。

上一篇:python中len代表什么

下一篇:python中//

大家都在看

python时间格式

python ord和chr

python中的yield

python自定义异常

python list.pop

python的for i in range

npm config set python

python代码简单

python读取文件夹

python中turtle

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

Laravel 中文站