set
特点:天生去重,无序,没有下标
l = [1,1,2,2,3,3,4,4,5,5]
l2 = {1,2,3,4,5,5,6,8}
s = set(l)
print(s)
print(l2)
输出结果:
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6, 8}
- 定义空集合:
l2 = set()
交集,并集,差集
新增元素
l3 = set()
l3.add(8)
删除元素
l2 = {1,2,5,6,8}
l2.remove(8)
把一个集合加入到另一个集合里
l = [1,1,2,2,3,3,4,4,5,5]
l2 = {1,2,5,6,8}
l2.update(l)
交集(常用):intersection方法,&方法
stu1 = ['fd','wxl','zjr','lhy']
stu2 = ['fd','wxl','dsx','cc']
stu1_set = set(stu1)
stu2_set = set(stu2)
print(stu1_set.intersection(stu2_set))
print(stu1_set&stu2_set)
import string
password = 'abc123A'
password_set = set(password)
if password_set & set(string.digits) and password_set & set(string.ascii_lowercase) \
and password_set & set(string.ascii_uppercase):
print('密码合法')
else:
print('不合法')
并集(常用):union方法,|方法
s1 = {1,2,3,4}
s2 = {4,5,6,7}
print(s1.union(s2))
print(s1 | s2)
差集(用得少):在一个集合里存在,在另一个集合不存在
s1 = {1,2,3,4}
s2 = {4,5,6,7}
print(s1.difference(s2))
print(s1-s2)
输出结果:
{1, 2, 3}
{1, 2, 3}
对称差集(用的少):去除在多个集合里同事存在的元素
s1 = {1,2,3,4}
s2 = {4,5,6,7}
print(s1^s2)
print(s1.symmetric_difference(s2))
输出结果:
{1, 2, 3, 5, 6, 7}
{1, 2, 3, 5, 6, 7}