python set集合排序_Python Set集合

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}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值