list和dict的操作
li = [11,22,33,44,55,66,77,88,99,90]
dic = {'k1':"大于66",'k2':"小于等于66"}
如以上所示,将所有li列表里面大于66的值保存至字典的第一个key,小于66的保存至第二个key中:
例子:
1 #coding:utf-8 2 ''' 3 li = [11,22,33,44,55,66,77,88,99,90] 4 dic = {'k1':"大于66",'k2':"小于等于66"} 5 将li列表里面大于66的值保存至字典的第一个key,小于66的保存至第二个key中 6 ''' 7 8 9 #例1 10 dic = {} 11 li_max = [] 12 li_mix = [] 13 li = [11,22,33,44,55,66,77,88,99,90] 14 for n in li: 15 if n > 66: 16 li_max.append(n) 17 elif n <= 66: 18 li_mix.append(n) 19 dic["k1"] = li_mix 20 dic["k2"] = li_mix 21 print(dic) 22 23 24 #例2 25 li = [11,22,33,44,55,66,77,88,99,90] 26 dic = {} 27 for n in li: 28 if n >66: 29 if 'k1' in dic.keys(): 30 dic["k1"].append(n) 31 else: 32 dic['k1'] = [n] 33 34 elif n <= 66: 35 if 'k2' in dic.keys(): 36 dic['k2'].append(n) 37 else: 38 dic['k2'] = [n] 39 print(dic) 40 41 42 #例3 43 #利用defaultdict默认字典(dict的value为list类型) 44 from collections import defaultdict 45 li = [11,22,33,44,55,66,77,88,99,90] 46 dic = defaultdict(list) 47 for n in li: 48 if n >66: 49 dic["k1"].append(n) 50 elif n <= 66: 51 dic['k2'].append(n) 52 print(dic)