1.统计字符
统计字符串中每个字符出现的次数
s = 'l like summer very much' #去掉空格 s = s.replace(" ","") d = dict() for i in s:if i in d:d[i] += 1else:d[i] = 1 for i in d:print(i,d[i])
2.求不重复的随机数
#导入随机数 import random a = int(input("请输入随机数的范围:")) n = int(input("请输入随机数的个数:")) s = set() while len(s) < n :i = random.randint(1,a)s.add(i) print(s)
3.设计不可变集合
set 可变集合
可读可写的集合
基本功能:关系检测和元素去重
frozenset 不可变集合
只读的set集合
基本功能:定义哈希值
将两个城市定为键,将城市距离定义为值
city_discance = {} key1 = frozenset(["Beijing","Tianjing"]) key2 = frozenset(["Shanghai","Zhejinag"]) key3 = frozenset(["Chongqing","Chengdu"]) city_discance[key1] = 123 city_discance[key2] = 456 city_discance[key3] = 789 print(city_discance)
4.创建用户登录系统
#统计用户名和密码 user = {} #统计输入密码的次数为3 count = 3 while True:print("*"*40)name = input("请输入用户名:")if name in user:while count >= 0:pw = input("请输入密码:")if user[name] == pw:print("密码正确,登录成功!")breakelse:print("登录失败,你还有%d次机会"%count)count -= 1else:print("密码输入次数已到")else:f = input("用户名不存在,是否创建用户名[y/n]")if f == "y":while True:name = input("请输入用户名: ")if name in user:print("用户名已存在")else:pw = input("请输入密码:")repw = input("请再次输入密码")if pw == repw:user[name] =1 pwprint("用户创建成功")breakelse:print("密码输入有误")else:print("退出系统,欢迎下次再来")