day14 Python集合

定义:由不同元素组成的集合,集合是一组无序排列的可hash值,可以作为字典的key

1、不同元素。2、无序。3、集合中元素必须是不可变类型(数字,字符串,元祖)

特性:集合的目的是将不同的值存放在一起,不同的集合间用来做关系运算,无需纠结于集合中得单个值

s = set("hello")
print(s)
s = set(['charon','charon','pluto'])
print(s)

结果:
{'o', 'e', 'l', 'h'}
{'pluto', 'charon'}

 参数

add添加

s = {1,2,3,4,5}
s.add('a')
s.add('3')
s.add(6)
s.add(3)
print(s)

结果:
{1, 2, 3, 4, 5, '3', 6, 'a'}

 clear清空

s = {1,2,3,4,5}
s.clear()
print(s)

结果:
set()

 copy复制

s = {1,2,3,4,5}
s1 = s.copy()
print(s1)

结果:
{1, 2, 3, 4, 5}

 pop删除(随机删除)

s = {'s',1,2,3,4,5}
s.pop()
print(s)

结果:
{2, 3, 4, 5, 's'}

remove删除(指定删除,删除的元素不存在会报错) 

s = {'sb',1,2,3,4,5}
s.remove("sb")
print(s)

结果:
{1, 2, 3, 4, 5}

 discard删除(指定删除,删除元素不存在也不会报错)

s = {'s',1,2,3,4,5}
s.discard('hellossssss')
s.discard('s')
print(s)

结果:
{1, 2, 3, 4, 5}

猜你喜欢

转载自www.cnblogs.com/charon2/p/10356140.html