python:集合

集合

  1.集合的必要

    题目:如果培训班中有2个报名课程,有的人报名linux,有的人报名python ,要求将即报名linux,又报名python的同学,挑出。如果是用之前的列表方法如下:

 1 python_list=['stu1','stu2','stu3','stu4','stu5','stu6','stu7']
 2 linux_list=['stu2','stu5','stu8','stu9','stu10']
 3 both=[]
 4 for i in python_list:
 5     if i in linux_list:
 6         both.append(i)
 7 print(both)
 8 
 9 
10 #《》《》《》打印结果《》《》《》
11 ['stu2', 'stu5']

    ※那么集合又会给我们带来哪些便利呢?

  2.集合的关系运算

    集合是一个无序不重复的元素集。那么如果设定的列表中插入重复的元素后,如何去重呢?

    ※去重

1 >>> a=['a','a','b','b']
2 >>> a
3 ['a', 'a', 'b', 'b']
4 >>> a=set(a)
5 >>> a
6 {'a', 'b'}
7 >>> a=[i for i in a]
8 >>> a
9 ['a', 'b']

    接下来,说一下,集合中的关系运算 并集|、交集&,差集-,对称差集^

 1 >>> a=set('hello')
 2 >>> b=set('welcome')
 3 >>> a
 4 {'h', 'e', 'l', 'o'}
 5 >>> b
 6 {'m', 'c', 'e', 'o', 'w', 'l'}
 7 >>> a|b
 8 {'m', 'c', 'h', 'e', 'o', 'w', 'l'}
 9 >>> a&b
10 {'e', 'l', 'o'}
11 >>> b-a
12 {'w', 'c', 'm'}
13 >>> a-b
14 {'h'}
15 >>> a^b
16 {'h', 'm', 'w', 'c'}

    学过数学的集合,这个就不难理解了。

    子集<=  >= 

  3.集合的方法

    update() 将()里面的内容更新到集合中,并自动去重。

1 >>> a=set('hello')
2 >>> a
3 {'h', 'e', 'l', 'o'}
4 >>> a.update('asdfasd')
5 >>> a
6 {'a', 'd', 'f', 'h', 's', 'e', 'o', 'l'}

     add()是将参数作为一个元素加入到集合中。这一点要跟update()不同。

      

1 >>> a=set('hello')
2 >>> a
3 {'h', 'e', 'l', 'o'}
4 >>> a.update('asdfasd')
5 >>> a
6 {'a', 'd', 'f', 'h', 's', 'e', 'o', 'l'}
7 >>> a.add("语文")
8 >>> a
9 {'a', 'd', 'f', 'h', 's', 'e', 'o', '语文', 'l'}

 

    clear()清空、copy()浅拷贝、different_update()跟并集、交集、对称差集的update相同,都是运算后,更新引用集合的内容。

    集合的删除

      

 1 >>> a=set('python')
 2 >>> a.pop()  #随机删除了一个
 3 'y'
 4 >>> a
 5 {'t', 'n', 'h', 'o', 'p'}  
 6 >>> a.remove('t')
 7 >>> a.remove('t') #当集合中没有这个元素的时候报错
 8 Traceback (most recent call last):
 9   File "<stdin>", line 1, in <module>
10 KeyError: 't'
11 >>> a.discard('p')
12 >>> a.discard('p')#当集合中没有这个元素的时候,不会报错
13 >>> a.discard('p')
14 >>> a.discard('p')
15 >>> a
16 {'n', 'h', 'o'}

 

 

 

 

 

 

 

    

 

posted @ 2016-10-25 21:28  bkywanqian  阅读(209)  评论(0编辑  收藏  举报