python中set集合简单使用教程

python中的set集合使用非常简便。下面从创建,添加,删除,交集,并集和差集等方面做简要阐述。

创建:无须定义,使用时创建即可

添加:有add()和update(),add()把整体作为一个元素添加到集合中,update()把要添加的元素分为一个个单独的元素添加到集合中

交集|并集|差集:直接见示例代码中的运行结果。


示例代码

#coding=utf-8

#创建set集合
a = set('abc')
#使用add()向set集合中添加元素
a.add('def')
#使用update()向set集合中添加元素
a.update('gh')

#遍历set集合
for item in a:
    print (item)

print ("---分割线-删除def---")
a.remove('def')
#遍历set集合
for item in a:
    print (item)

s1 = set('abc')
s2 = set('bcd')

print ("s1=abc,s2=bcd---交集|并集|差集---")
#交集
b = s1 & s2

#并集
c = s1 | s2

#差集
d = s1 - s2

print ("交集=%s,并集=%s,差集=%s",b,c,d)

运行结果




猜你喜欢

转载自blog.csdn.net/jp_666/article/details/79393808
今日推荐