1 cars = [‘鲁A32444‘,‘鲁B12333‘,‘京B8989M‘,‘黑C49678‘,‘黑C46555‘,‘沪 B25041‘] 2 locals = {‘沪‘:‘上海‘, ‘黑‘:‘黑龙江‘, ‘鲁‘:‘山东‘, ‘鄂‘:‘湖北‘, ‘湘‘:‘湖南‘}
第一种做法:
dic = {} all = "".join(cars) #把所有车牌连接起来.replace(" ","") for i in locals: num = all.count(i) #通过count计数 dic[locals[i]]=num #将地市和数量添加到字典 print(dic)
结果对照:
{‘上海‘: 1, ‘黑龙江‘: 2, ‘山东‘: 2, ‘湖北‘: 0, ‘湖南‘: 0}
第二种做法:
1 dic = {} 2 for i in cars: 3 c = i[0] #循环取到所有车牌的地市简称 4 if c in locals: #如果简称在地市对应表里则添加 5 dic[locals.get(c)] = dic.get(locals.get(c),0)+1 #将获取到的添加到字典里 6 print(dic)
结果对照:
1 {‘山东‘: 2, ‘黑龙江‘: 2, ‘上海‘: 1}
原文地址:https://www.cnblogs.com/NoteBook3013/p/10238349.html
时间: 2024-10-09 14:58:48