python之集合(set)学习

  • 2020 年 1 月 17 日
  • 筆記

集合(set)

集合是一个无序的不重复元素序列,使用大括号({})、set()函数创建集合。

注意:创建一个空集合必须用set()而不是{},因为{}是用来创建一个空字典。

集合是无序的、不重复的、没有索引的

1 a = {'hello','ni','hao','hi','ni','hao'}  2  3 print(a)     # 输出结果没有重复项,且无序  4 # print(a[1])   # TypeError: 'set' object does not support indexing

输出结果:

{'ni', 'hao', 'hello', 'hi'}

添加集合元素

添加单个元素:

1 a = {'hello','ni','hao','hi','ni','hao'}  2 print(a)  3  4 a.add('wo')  5 print(a)  6  7 a.add('hi')     # 如果元素已存在,则不进行任何操作。  8 print(a)     

输出结果:

{'hi', 'ni', 'hao', 'hello'}  {'hello', 'hi', 'wo', 'ni', 'hao'}  {'hello', 'hi', 'wo', 'ni', 'hao'}

添加多个元素、列表元素、字典元素

 1 a = {'hello','ni','hao','hi','ni','hao'}   2 print(a)   3   4 a.update("me", 'da')   5 print(a)   6   7 a.update({'user': 'name', 'pwd': 'mima'})   8 print(a)   9  10 print(len(a))  11 a.update([1, 2, 3, 4])  12 print(a)  13  14 a.update(['abc', 'word', 'x'])  15 print(a)

输出结果:

{'hi', 'hao', 'hello', 'ni'}  {'hello', 'hao', 'e', 'ni', 'hi', 'd', 'a', 'm'}  {'hello', 'hao', 'e', 'ni', 'hi', 'user', 'pwd', 'd', 'a', 'm'}  {1, 2, 3, 4, 'hello', 'hao', 'e', 'ni', 'hi', 'user', 'pwd', 'd', 'a', 'm'}  {1, 2, 3, 4, 'hello', 'abc', 'hao', 'e', 'ni', 'hi', 'user', 'pwd', 'd', 'word', 'a', 'm', 'x'}

输出结果有些出人意料,使用add添加单个元素时,不管该元素时单个字符还是字符串,都作为一个元素添加,而使用update则将字符串元素拆开为单个字符添加。

而且添加的元素为字典时,可以发现,key值是按照字符串添加的,而value值也是拆开为单个字符添加。

添加的元素为列表时,是将列表元素拆开,作为一个个单独的元素添加进集合,即使列表元素中有字符串,但是不在拆分该字符串。

删除集合元素

删除集合元素有三种方法:set.remove()、set.discard()、set.pop()

 1 a = {'hello','ni','hao','hi','ni','hao'}   2   3 a.remove('hao')   4 print(a)   5   6 # a.remove('nihao')   # 如果元素不存在,会发生错误   7 # print(a)   8 a.discard('nihao')  # 如果元素不存在,不会发生错误   9 print(a)  10  11 a.pop()     # 随机删除集合中的一个元素,在交互模式中,删除集合中的第一个元素(排序后的第一个元素)  12 print(a)

输出结果:

{'ni', 'hi', 'hello'}  {'ni', 'hi', 'hello'}  {'hi', 'hello'}

清空集合元素:

1 a = {'hello','ni','hao','hi','ni','hao'}  2  3 a.clear()  4 print(a)

输出结果:

set()

遍历集合

因为集合是无序的,所以不能使用索引,那么只能使用for循环来遍历。

1 a = {'hello','ni','hao','hi','ni','hao'}  2  3 for x in a:  4     print(x)

输出结果:

hao  ni  hi  hello

学到这里,Python的基本数据类型已经简单的介绍完了,但是肯定不是这么点,还有更深更细节的知识就不是现阶段应该学的,那需要以后慢慢积累,多加练习才能掌握的。