python中的dict是一个重要的数据类型,用”键”(key)来索引,表示为dict(key: val, …),有以下特征:
bag = {'apple', 'orange', 'cherry', 'apple', 'apple', 'cherry', 'blueberry'}
count = {}
for fruit in bag:
count[fruit] += 1
print(count)
正常定义字典,报错如下:
from collections import defaultdict
bag = {'apple', 'orange', 'cherry', 'apple', 'apple', 'cherry', 'blueberry'}
count = defaultdict(int)
for fruit in bag:
count[fruit] += 1
print(count)
输出如下:
from collections import defaultdict
def zero():
return 0
dic = defaultdict(zero)
dic['bbb']
print(dic)
from collections import defaultdict
s = 'mississippi'
d = defaultdict(int)
for k in s:
d[k] += 1
print(d)
from collections import defaultdict
s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
d = defaultdict(set)
for k, v in s:
d[k].add(v)
print(d)
from collections import defaultdict
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
d[k].append(v)
print(d)
from collections import defaultdict
### 将每种球与其总数量统计出来
lis = [('红色',1),('白色',2),('绿色',3),('紫色',1),('红色',1),('白色',1),('红色',1),('粉色',1),]
dic = defaultdict(list)
for i in lis:
dic[i[0]].append(i[1])
dic = dict(dic)
print(dic)
for i in dic:
dic[i] = sum(dic[i])
print(dic)
实现一个简单的三次登陆失败锁定的例子:
# -*- coding:utf-8 -*-
from collections import defaultdict
# 默认value设置成0
dic = defaultdict(int)
# 这里设置一个flag,while循环的额条件是flag;
# 如果循环内还有一层循环,跳出内层循环若需要跳出整个循环可以将flag设置成False!
flag = True
while flag:
username = input('用户名:').strip()
password = input('密码:').strip()
# 先判断账号有没有被锁定
with open('locked','r',encoding='utf-8')as f:
for line in f:
if username == line.strip():
print('该账号已被锁定!')
flag = False
break
# 默认字典 —— 确保 “每个用户都有三次机会”
if dic[username] < 2:
with open('userinfo','r',encoding='utf-8')as f:
for line in f:
usr,pwd = line.strip().split('|')
if usr == username and pwd == password:
print('登陆成功!')
# 如果想登陆成功后退出while大循环,可以将flag设置为False
flag = False
# 这个break只是退出for循环
break
else:
dic[username] += 1
print('登录失败!用户名或密码错误!')
else:
with open('locked','a',encoding='utf-8')as f:
f.write(username+'\n')
print('账号被锁定!')
break
from collections import defaultdict
a = ['a,1', 'b,3,22', 'c,3,4', 'f,5', ]
b = ['a,2', 'b,4', 'w,12', 'd,2','c,123']
dic = defaultdict(str)
for i in a:
dic[i[0]] = i
dic = dict(dic)
print(dic)
for i in b:
if i[0] in dic:
dic[i[0]] += i[1:]
else:
dic[i[0]] = i
print(dic)
print(list(dic.values()))