前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python set集合排序_Python Set集合「建议收藏」

python set集合排序_Python Set集合「建议收藏」

作者头像
全栈程序员站长
发布2022-08-15 21:26:18
1K0
发布2022-08-15 21:26:18
举报

大家好,又见面了,我是你们的朋友全栈君。

Python Set集合

Python 中的集合,和数学中的集合概念一样,用来保存不重复的元素,即集合中的元素都是唯一的,互不相同。

从形式上看,和字典类似,Python 集合会将所有元素放在一对大括号 {} 中,相邻元素之间用“,”分隔,如下所示:

{element1,element2,…,elementn}

其中,elementn 表示集合中的元素,个数没有限制。 从内容上看,同一集合中,只能存储不可变的数据类型,包括整形、浮点型、字符串、元组,无法存储列表、字典、集合这些可变的数据类型,否则 Python 解释器会抛出 TypeError 错误。

由于 Python 中的 set 集合是无序的,所以每次输出时元素的排序顺序可能都不相同。

其实,Python 中有两种集合类型,一种是 set 类型的集合,另一种是 frozenset 类型的集合,它们唯一的区别是,set 类型集合可以做添加、删除元素的操作,而 forzenset 类型集合不行。

Python 提供了 2 种创建 set 集合的方法,分别是使用 {} 创建和使用 set() 函数将列表、元组等类型数据转换为集合。

1) 使用{}创建

在 Python 中,创建 set 集合可以像列表、元素和字典一样,直接将集合赋值给变量,从而实现创建集合的目的,其语法格式如下:

setname = {element1, element2,…elementn}

举个例子:

a = {1, ‘x’, ‘x’, (7,8,9),3}

print(a)

运行结果为:

{1, (7, 8, 9), 3, ‘x’}

2) Create Set with set()

set() 函数为 Python 的内置函数,其功能是将字符串、列表、元组、range 对象等可迭代对象转换成集合。该函数的语法格式如下:

setname = set(iteration)

注意,如果要创建空集合,只能使用 set() 函数实现。因为直接使用一对 {},Python 解释器会将其视为一个空字典。

访问set集合元素

由于集合中的元素是无序的,因此无法向列表那样使用下标访问元素。访问集合元素最常用的方法是使用循环结构,将集合中的数据逐一读取出来。

Delete set

Like other sequence type. We can use del() to delete set as well.

del(set1)

Operations of Set

1.Add Element

To add elements to the set collection, we can use the add() provided by the set to achieve.

for example:

>>>setA = {‘x’,’y’,’z’}

>>>print(setA)

>>>setA.add(147)

{‘y’, 147, ‘z’, ‘x’}

It should be noted that the elements added by the method add() can only be numbers, strings, tuples or boolean (True and False) values. The data such as lists, dictionaries, and collections cannot be added, otherwise Python will report a TypeError

2. Remove element

Remove the specific element from a Set, we can use method remove() to complete it.

setname.remove(element)

if the element not exist in the set. the KeyError will be reported.

>>> setA.remove(‘w’)

Traceback (most recent call last):

File “”, line 1, in KeyError: ‘w’

3.union, intersection, difference and symmetric difference.

交集、并集、差集,对称差集

>>> setA = {5,6,7}

>>> setB = {7,8,9}

Operation

Operator

Concept

Example

union

&

take the common elements of these set

>>> setA & SetB

{7}

intersection

|

take all elements of these set

>>> setA | setB

{5,6,7,8,9}

difference

Take elements in a set that are not in another set

>>> setA – setB

{5,6}

>>> setB – setA

{8,9}

symmetric difference

^

Take the elements in sets A and B that do not belong to A&B

>>>setA ^ setB

{5, 6, 8, 9}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/134461.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022年5月2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档