字典经典习题
1.有字符串 "k:1|k1:2|k2:3|k3:4" 处理成字典 {'k':1,'k1':2....}
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 # 转换成字典(面试题) 这里面主要就是一个切割 2 str1 = "k:1|k1:2|k2:3|k3:4" 3 dic = {} 4 lst = str1.split("|") 5 for l in lst: 6 lst2 = l.split(":") 7 dic[lst2[0]] = lst2[1] 8 print(dic)
2.元素分类:有如下值li= [11,22,33,44,55,66,77,88,99,90],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66的所有值列表, 'k2': 小于66的所有值列表}
# 解法1 最撮
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 # 最直接的先初始化两个key 如果全部在一边就不太好 2 dic = {'k1': [], "k2": []} 3 li = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90] 4 for num in li: 5 if num > 66: 6 dic["k1"].append(num) 7 else: 8 dic["k2"].append(num) 9 print(dic)
# 解法2 get方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 dic = {} 2 for num in li: 3 if num > 66: 4 if dic.get("k1") == None: 5 dic["k1"] = [num] 6 # 第一次指定key1的值得时候,一定要是列表的形式 7 8 else: 9 dic["k1"].append(num) 10 # 进入列表就是append 11 else: 12 if dic.get("k2") == None: 13 dic["k2"] = [num] 14 else: 15 dic["k2"].append(num) 16 17 print(dic)
#解法3 setdefault 对get的进一步抽象
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 dic = {} 2 for num in li: 3 if num < 66: 4 dic.setdefault('key1', []).append(num) 5 else: 6 dic.setdefault('key2', []).append(num) 7 print(dic)
# 根据数字长度分类数据
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 a = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 32769, 65535,955215622] 2 a = [str(i) for i in a] 3 # print(a) 4 dic = {} 5 for i in a: 6 l = len(i) 7 dic.setdefault(l, []).append(i) 8 print(dic)
3.统计车流量
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 # coding:utf-8 2 # 统计每个省的车辆数目 3 # 如果能get到 那么加1即可 否则初始化为1 4 cars = ['鲁A', '鲁B', '京C', '黑A', '黑b'] 5 locals1 = {'鲁': '山东', '京': '北京', '黑': '黑龙江'} 6 dic = {} 7 for car in cars: 8 if dic.get(car[0]): 9 dic[car[0]] += 1 10 else: 11 dic[car[0]] = 1 12 print(dic) 13 14 # 那么问题来了 这个可以用setdefault一行搞定吗? 15 # 我还没想到!!!
4.一道列表的递归嵌套面试题
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 a = [1, 2] 2 a[1] = a 3 print(a) 4 """ 5 [1, [...]] 6 """