【从零学习python 】23. Python中集合(set)的使用方法和常见操作

set的使用

集合(set)是一个无序的不重复元素序列,可以使用大括号 { } 或者 set() 函数创建集合。

注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。

创建格式

parame = {value01, value02, ...} 或者 set(value)

添加元素

语法格式如下:

s.add(x)

将元素 x 添加到集合 s 中,如果元素已存在,则不进行任何操作。

thisset = set(("Google", "Runoob", "Taobao"))
thisset.add("Facebook")
print(thisset)

还有一个方法,也可以添加元素,且参数可以是列表,元组,字典等,语法格式如下:

s.update(x)

x 可以有多个,用逗号分开。

thisset = set(("Google", "Runoob", "Taobao"))
thisset.update({
    
    1, 3})
print(thisset)

thisset.update([1, 4], [5, 6])
print(thisset)

移除元素

语法格式如下:

s.remove(x)

将元素 x 从集合 s 中移除,如果元素不存在,则会发生错误。

thisset = set(("Google", "Runoob", "Taobao"))
thisset.remove("Taobao")
print(thisset)

此外还有一个方法也是移除集合中的元素,且如果元素不存在,不会发生错误。格式如下所示:

s.discard(x)

thisset = set(("Google", "Runoob", "Taobao"))
thisset.discard("Facebook")
print(thisset)

我们也可以设置随机删除集合中的一个元素,语法格式如下:

s.pop()

thisset = set(("Google", "Runoob", "Taobao", "Facebook"))
x = thisset.pop()

print(x)
print(thisset)

set常见方法列表

方法 描述
add() 为集合添加元素
clear() 移除集合中的所有元素
copy() 拷贝一个集合
pop() 随机移除元素
remove() 移除指定元素
union 返回两个集合的并集
update() 给集合添加元素
difference() 返回多个集合的差集
difference_update() 移除集合中的元素,该元素在指定的集合也存在。
discard() 删除集合中指定的元素
intersection() 返回集合的交集
intersection_update() 删除集合中的元素,该元素在指定的集合中不存在。
isdisjoint() 判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。
issubset() 判断指定集合是否为该方法参数集合的子集。
issuperset() 判断该方法的参数集合是否为指定集合的子集
symmetric_difference() 返回两个集合中不重复的元素集合。
symmetric_difference_update() 移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。

练习

有一个无序且元素数据重复的列表nums, nums=[5,8,7,6,4,1,3,5,1,8,4],要求对这个列表里的元素去重,并进行降序排序。

方法一:调用列表的sort方法

nums2 = list(set(nums))
nums2.sort(reverse=True)
print(nums2)

方法二:使用sorted内置函数

print(sorted(list(set(nums)), reverse=True))

进阶案例

【Python】Python 实现猜单词游戏——挑战你的智力和运气!

【python】Python tkinter库实现重量单位转换器的GUI程序

【python】使用Selenium获取(2023博客之星)的参赛文章

【python】使用Selenium和Chrome WebDriver来获取 【腾讯云 Cloud Studio 实战训练营】中的文章信息

使用腾讯云 Cloud studio 实现调度百度AI实现文字识别

【玩转Python系列【小白必看】Python多线程爬虫:下载表情包网站的图片

【玩转Python系列】【小白必看】使用Python爬取双色球历史数据并可视化分析

【玩转python系列】【小白必看】使用Python爬虫技术获取代理IP并保存到文件中

【小白必看】Python图片合成示例之使用PIL库实现多张图片按行列合成

【小白必看】Python爬虫实战之批量下载女神图片并保存到本地

【小白必看】Python词云生成器详细解析及代码实现

【小白必看】Python爬取NBA球员数据示例

【小白必看】使用Python爬取喜马拉雅音频并保存的示例代码

【小白必看】使用Python批量下载英雄联盟皮肤图片的技术实现

【小白必看】Python爬虫数据处理与可视化

【小白必看】轻松获取王者荣耀英雄皮肤图片的Python爬虫程序

【小白必看】利用Python生成个性化名单Word文档

【小白必看】Python爬虫实战:获取阴阳师网站图片并自动保存

小白必看系列之图书管理系统-登录和注册功能示例代码

小白实战100案例: 完整简单的双色球彩票中奖判断程序,适合小白入门

Geospatial data processing and visualization using geopandas and shapely (.shp)

Use selenium to crawl Maoyan movie list data

Detailed explanation of the principle and implementation of image enhancement algorithm Retinex

Getting Started Guide to Crawlers (8): Write weather data crawler programs for visual analysis

Introductory Guide to Crawlers (7): Using Selenium and BeautifulSoup to Crawl Douban Movie Top250 Example Explanation [Reptile Xiaobai must watch]

Getting Started Guide to Crawlers (6): Anti-crawlers and advanced skills: IP proxy, User-Agent disguise, Cookie bypass login verification and verification code identification tools

Introductory Guide to Crawlers (5): Distributed Crawlers and Concurrency Control [Implementation methods to improve crawling efficiency and request rationality control]

Getting started with crawlers (4): The best way to crawl dynamic web pages using Selenium and API

Getting Started Guide to Crawlers (3): Python network requests and common anti-crawler strategies

Getting started with crawlers (2): How to use regular expressions for data extraction and processing

Getting started with reptiles (1): Learn the basics and skills of reptiles

Application of Deep Learning Model in Image Recognition: CIFAR-10 Dataset Practice and Accuracy Analysis

Python object-oriented programming basics and sample code

MySQL database operation guide: learn how to use Python to add, delete, modify and query operations

Python file operation guide: encoding, reading, writing and exception handling

Use Python and Selenium to automate crawling#【Dragon Boat Festival Special Call for Papers】Explore the ultimate technology, and the future will be due to you"Zong" #Contributed articles

Python multi-thread and multi-process tutorial: comprehensive analysis, code cases and optimization skills

Selenium Automation Toolset - Complete Guide and Tutorials

Python web crawler basics advanced to actual combat tutorial

Python introductory tutorial: master the basic knowledge of for loop, while loop, string operation, file reading and writing and exception handling

Pandas data processing and analysis tutorial: from basics to actual combat

Detailed explanation of commonly used data types and related operations in Python

[Latest in 2023] Detailed Explanation of Six Major Schemes to Improve Index of Classification Model

Introductory Python programming basics and advanced skills, web development, data analysis, and machine learning and artificial intelligence

Use 4 regression methods to draw prediction result charts: vector regression, random forest regression, linear regression, K-nearest neighbor regression
** [Learn python from zero] 18. Detailed explanation of basic operations of Python lists (1) **

Guess you like

Origin blog.csdn.net/qq_33681891/article/details/132289940