Python-集合

 1 #!/usr/bin/env python    
 2 # -*- coding: utf-8 -*-
 3 print("----集合学习----")
 4 # 集合一次性存储多个数据,特点:去重复数据。没有重复数据时使用集合
 5 set1 = {10, 20, 30, 40}
 6 print(set1)  # 打印出来集合没有顺序,所以不支持下标
 7 
 8 print("集合的创建操作:")
 9 # 非空集合的创建
10 set2 = {10, 20, 10, 30, 30}
11 print(set2)  # 自动去重,打印时不体现重复数据
12 # set()方法创建集合
13 set3 = set("abc")
14 print(set3) # 集合会将内容拆开,单独体现
15 
16 # 创建空集合
17 set4 = set()
18 set5 = {}
19 print(type(set4), type(set5))  # 创建空集合只能使用set()方法,{}创建的是字典
20 
21 print("集合增加数据:")
22 # add()方法增加,增加的是单一数据,序列报错
23 set6 = {30, 20}
24 set6.add("aaa")
25 print(set6)  # 集合是可变数据类型,增加的数据集合已有,则不实际增加到集合.set6.add([1, 2, 3]) 报错
26 # update()方法,增加的是序列,非序列报错
27 set7 = {30, 20}
28 set7.update([10, 20, 'aa', 10])
29 print(set7)  # 增加的是序列,update('bb')则报错
30 
31 print("集合删除数据:")
32 set8 = {10, 20, 30, 40, 50}
33 # remove()删除指定数据,数据不存在报错
34 set8.remove(20)
35 print(set8)
36 # discard()删除指定数据,数据不存也不报错
37 set8.discard(10)
38 set8.discard(10)
39 print(set8)
40 # pop()随机删除集合中某个数据,并返回这个数据
41 print(set8.pop(), set8)
42 
43 print("集合查找数据:")
44 set9 = {10, 20, 30, 40, 50}
45 # in 或 not in
46 print(10 in set9)
47 print(10 not in set9)

运行结果:

 1 ----集合学习----
 2 {40, 10, 20, 30}
 3 集合的创建操作:
 4 {10, 20, 30}
 5 {'a', 'c', 'b'}
 6 <class 'set'> <class 'dict'>
 7 集合增加数据:
 8 {'aaa', 20, 30}
 9 {10, 20, 30, 'aa'}
10 集合删除数据:
11 {40, 10, 50, 30}
12 {40, 50, 30}
13 40 {50, 30}
14 集合查找数据:
15 True
16 False

 

posted @ 2020-04-22 23:19  君,子觞  阅读(138)  评论(0)    收藏  举报