文章目录
1.集合的定义
(1)集合:集合与数组元组一样,也用于存储数据;只是存储的数据元素不可重复;数据类型可变
(2)特性:
- 数据元素不可重复
- 集合内部会对数据元素自动按一定顺序处理,但不是自动排序
- 无切片,无索引
(3)定义一个空集合:s=set([])
(4)类型:set
s={}
不能这样默认定义一个集合,默认类型非集合而是dict字典
2.集合的常用方法
2.1 集合的成员操作符(in)
>>> s={1,2,3.5,'hello','people'}
>>> s
{'people', 1, 'hello', 2, 3.5}
>>> 1 in s
True
>>> 'python ' in s
False
>>> 3.5 in s
True
>>> '3.5' in s
False
>>> 'hello' not in s
False
>>> 1 not in s
False
>>> 20 not in s
True
>>>
2.2 集合的for循环
2.3 集合元素的添加(add)
集合中元素添加位置与元素存储位置不同
>>> s.add(0)
>>> s
{'people', 1, 'hello', 2, 3.5, 0}
>>> s.add('bye')
>>> s
{'people', 1, 'hello', 2, 3.5, 0, 'bye'}
>>> s.add(5)
>>> s
{'people', 1, 'hello', 2, 3.5, 0, 5, 'bye'}
>>> s.add(10)
>>> s
{'people', 1, 'hello', 2, 3.5, 0, 5, 10, 'bye'}
2.4 集合元素删除(pop|remove)
(1)pop
弹出元素,并未删除元素数据
>>> s
{'people', 1, 'hello', 2, 3.5, 0, 5, 10, 'bye'}
>>> s.pop()
'people'
>>> s.pop(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
(2)remove
指定元素删除
>>> s.remove(2)
>>> s
{1, 'hello', 3.5, 0, 5, 10, 'bye'}
>>> s.remove(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: -1
>>> s.remove(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 4
>>> s.remove(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 2
>>> s
{1, 'hello', 3.5, 0, 5, 10, 'bye'}
>>> s.remove('bye')
>>> s
{1, 'hello', 3.5, 0, 5, 10}
>>>
2.5 多个集合的交集、并集、差集和对等差分
(1)交集 (& union)
>>> s1={1,3,4,5,7}
>>> s2={'hello',2,4,5,3}
>>> s1
{1, 3, 4, 5, 7}
>>> s2
{'hello', 3, 2, 4, 5}
>>> s1 | s2
{1, 'hello', 3, 4, 5, 2, 7}
>>> s1.union(s2)
{1, 'hello', 3, 4, 5, 2, 7}
>>>
(2)并集 (| intersection)
>>> s1.intersection(s2)
{3, 4, 5}
>>> s1&s2
{3, 4, 5}
(3)差集 (- difference)
s1中存在,s2中不存在的元素集合
>>> s1
{1, 3, 4, 5, 7}
>>> s2
{'hello', 3, 2, 4, 5}
>>> s1 -s2
{1, 7}
>>> s2 -s1
{'hello', 2}
>>> s1.difference(s2)
{1, 7}
>>> s2.difference(s1)
{'hello',2}
(4)对等差分(^ symmetric_difference)
并集-交集
>>> s2.symmetric_difference(s1)
{1, 'hello', 2, 7}
>>> s1 ^ s2
{1, 'hello', 2, 7}
>>> s2 ^ s1
{1, 'hello', 2, 7}
2.6 子集判断、不相交判断
(1)子集判断 (issubset)
A.issubset(B)
表示A是否是B的子集;返回值为bool类型
>>> s1.issubset(s2)
False
>>> s1
{1, 3, 4, 5, 7}
>>> s3={5,7}
>>> s3.issubset(s1)
True
(2)不相交判断(isdisjoint)
无相交判断
>>> s1
{1, 3, 4, 5, 7}
>>> s2={'helo'}
>>> s2
{'helo'}
>>> s2.isdisjoint(s1)
True
>>> s3
{5, 7}
>>> s2.isdisjoint(s3)
True
>>> s1.isdisjoint(s3)
False
>>> s1.isjoint(s3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'set' object has no attribute 'isjoint'
3. 集合的应用场景
3.1 列表的快速去重
li=[1,8,9,10,5,33,2,8,10,1]
print(list(set(li)))
华为机试题:
明明想在学校中请一些同学一起做一项问卷调查,为了实验的客观性
他先用计算机生成了N个1~1000之间的随机整数(N<=1000)
,N是用户输入的,对于
其中重复的数字,只保留一个,把其余相同的数字去掉,
不同的数对应着不同的学生的学号,
然后再把这些
数从小到大排序,按照排好的顺序去找同学做调查,
请你协助明明完成“去重”与排序工作
sorted()
import random
s = set([])
for i in range(int(input('N:'))):
s.add(random.randint(1,1000))
print(sorted(s))