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

python set()函数

作者:冥界少主   发布日期:2026-02-02   浏览:63

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

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

# 使用 set() 函数从列表创建集合,自动去除重复元素
my_list = [1, 2, 2, 3, 4, 4, 5]
my_set = set(my_list)
print("从列表创建的集合:", my_set)  # 输出: 从列表创建的集合: {1, 2, 3, 4, 5}

# 使用 set() 函数从字符串创建集合,每个字符作为集合的一个元素
my_string = "hello"
char_set = set(my_string)
print("从字符串创建的集合:", char_set)  # 输出: 从字符串创建的集合: {'l', 'o', 'e', 'h'}

# 集合的基本操作
set1 = {1, 2, 3}
set2 = {3, 4, 5}

# 并集
union_set = set1.union(set2)
print("并集:", union_set)  # 输出: 并集: {1, 2, 3, 4, 5}

# 交集
intersection_set = set1.intersection(set2)
print("交集:", intersection_set)  # 输出: 交集: {3}

# 差集
difference_set = set1.difference(set2)
print("差集 (set1 - set2):", difference_set)  # 输出: 差集 (set1 - set2): {1, 2}

解释说明:

  • set() 函数用于创建一个集合。集合是无序且不重复的元素集合。
  • 可以通过传递列表、元组或字符串等可迭代对象来创建集合,set() 会自动去除重复元素。
  • 集合支持常见的集合操作,如并集 (union)、交集 (intersection) 和差集 (difference)。

上一篇:python insert

下一篇:string在python中代表什么

大家都在看

python时间格式

pythoneval函数用法

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

python 私有函数

python ord和chr

python中的yield

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

Laravel 中文站