一分钟学会python编程_一分钟学Python|Python的集合

print(student) #显示集合以及去重功能

#判断 Tom 是否在集合中

if( 'Tom'instudent) :

print( 'true')

else:

print( 'false')

#集合间的运算

#创建集合

a = set( 'abcd')

b = set( 'abc')

#输出集合

print(a)

print(a-b) #a b的差集

print(a|b) #a b的并集

print(a&b) #a b的交集

print(a^b) #a b中不同时存在的元素

结果如下

{ 'Jim', 'Jack', 'Tom', 'Mary'}

true

{ 'b', 'd', 'a', 'c'}

{ 'd'}

{ 'd', 'a', 'b', 'c'}

{ 'b', 'a', 'c'}

{ 'd'}

集合的基本操作

1. 添加元素

语法格式如下:

s.add( x )

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

代码实例

>>>thisset = set(( "Google", "Baidu", "Taobao"))

>>>thisset.add( "Facebook")

>>>print(thisset)

{ 'Facebook', 'Google', 'Baidu', 'Taobao'}

>>>

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

s.update( x )

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

代码实例

>>>thisset = set(( "Google", "Baidu", "Taobao"))

>>>thisset.update({ 1, 3})

>>>print(thisset)

{ 1, 3, 'Google', 'Taobao', 'Baidu'}

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

>>>print(thisset)

{ 1, 3, 4, 5, 6, 'Google', 'Taobao', 'Baidu'}

>>>

2. 移除元素

语法格式如下:

s.remove( x )

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

>>>thisset = set(( "Google", "Baidu", "Taobao"))

>>>thisset.remove( "Taobao")

>>>print(thisset)

{ 'Google', 'Baidu'}

>>>thisset.remove( "Facebook") # 不存在会发生错误

Traceback (most recent call last):

File "", line 1, in

KeyError: 'Facebook'

>>>

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

s.discard( x )

代码实例

>>>thisset = set(( "Google", "Baidu", "Taobao"))

>>>thisset.discard( "Facebook") # 不存在不会发生错误

>>>print(thisset)

{ 'Taobao', 'Google', 'Baidu'}

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

s.pop

thisset = set(( "Google", "Baidu", "Taobao", "Facebook"))

x = thisset.pop

print(x)

==================结果================

Facebook

>>>

set 集合的 pop 方法会对集合进行无序的排列,然后将这个无序排列集合的左面第一个元素进行删除。

3. 清空集合

语法格式如下:

s.clear

代码实例

>>>thisset = set(( "Google", "Baidu", "Taobao"))

>>>thisset.clear

>>>print(thisset)

set

4. 计算集合元素个数

语法格式如下:

len(s)

计算集合 s 元素个数。

>>>thisset = set(( "Google", "Baidu", "Taobao"))

>>>len(thisset)

3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值