集合

集合

#集合天生可以去重

# l = [1,2,3,2,3,4,5,6,6,6,7,8,9]
# res = set(l)
# print(res)

# s = set()   #空集合
#
s1 = {1,2,3,4}

s2 = {4,5,6,7,1}
#交集
print(s1.intersection(s2))    #取交集
print(s1 & s2)  #用&取交集

stu1 = ['yln','dd','dwl','xuz']    #性能班

stu2 = ['yln','dk','dwl','xuz','zlj']  #自动化班



#并集
print(s1.union(s2))
print(s1 | s2)

#差集
print(s2 - s1)      #a里面有,b里面没有的
print(s1.difference(s2))

#对称差集
print(s2.symmetric_difference(s1))      #把a和b里面都有的去掉
print(s1 ^ s2)

#集合是无序的

s1.add('abc')
print(s1)
s1.remove('abc')
print(s1)

举个例子

#要求 必须包含大写字母,小写字母,数字,特殊字符

import string
password = input('输入密码:').strip()
if password:
    print('输入不为空')
else:
    print('密码不能为空')
pwd = set(password)     #转为集合
print('大写字母取',pwd.intersection(set(string.ascii_uppercase)))
print('小写字母取',pwd.intersection(string.ascii_lowercase))
print('数字取',pwd.intersection(string.digits))
print('特殊字符取',pwd.intersection(string.punctuation))
if pwd.intersection(set(string.ascii_uppercase)) and pwd.intersection(string.ascii_lowercase) and pwd.intersection(string.digits) and pwd.intersection(string.punctuation):
    print('密码合法!')
else:
    print('密码必须包含大写字母、小写字母、数字和特殊字符')


# string.ascii_uppercase
# string.ascii_lowercase
# string.digits
# string.punctuation

# if pwd & set(string.ascii_uppercase):


# 1.非空即真  非零即真
# s = ''
# s1 = []
# s2 = set()
# s3 = {}
# s4 = None
# s5 = ()

结果

输入密码:ASDjksdf90hjkadsf()hjkasdf8907(&)_*
输入不为空
大写字母取 {'A', 'D', 'S'}
小写字母取 {'f', 'a', 'j', 'd', 's', 'k', 'h'}
数字取 {'0', '7', '8', '9'}
特殊字符取 {'_', ')', '*', '(', '&'}
密码合法!
posted @ 2019-04-18 19:51  狂爷  阅读(95)  评论(0编辑  收藏  举报