1.元素分类: #[11,22,33,44,55,66,77,88,99,90] #将所有大于66的值保存至字典的一个key中 #将小于66的保存至第二个key中 #{‘k1‘:[77,88,99,90],‘k2‘:[11,22,33,44,55,66]} li = [11,22,33,44,55,66,77,88,99,90] dic = {‘k1‘:[],‘k2‘:[]} for i in li: if i > 66: dic[‘k2‘].append(i) else: dic[‘k1‘].append(i) dic1 = {} #key不确定的情况洗 for i in li: if i > 66: if ‘k2‘ in dic1.keys(): dic[‘k2‘].append(i) else: dic1[‘k2‘] = [i,] else: if ‘k1‘ in dic1.keys(): dic[‘k1‘].append(i) else: dic[‘k1‘]= [i,] #1.txt #yys|123|1 #eddy|123|1 #linux|123|1 ‘‘‘dic = { ‘yys‘:[123,1] ‘eddy‘:[123,1] ‘linux‘:[123,1] } ‘‘‘ dic = {} with open(‘1.txt‘,‘r‘) as file: for i in file.readlines(): line_list = i.strip().split(‘|‘)#每一行做为列表,把|分割的元素做为每一个元素 #[‘yys‘,‘123‘,‘1‘] dic[line_list[0]] = line_list[1:] print dic 2.collections 计数器 #计算元素出现了多少次 c1 = collections.Counter(‘aaaccdd‘) c2 = collections.Counter(‘aaacddee‘) Counter({‘a‘: 3, ‘c‘: 2, ‘d‘: 2}) Counter({‘a‘: 3, ‘e‘: 2, ‘d‘: 2, ‘c‘: 1}) #统计前几名3表示前三名 print c1.most_common(3) [(‘a‘, 3), (‘c‘, 2), (‘d‘, 2)] #update两个统计叠加 c1.update(c2) Counter({‘a‘: 6, ‘d‘: 4, ‘c‘: 3, ‘e‘: 2}) #打印元素 c1 = collections.Counter(‘aaaccdd‘) for i in c1.elements(): print i a a a c c d d #统计列表 li = [11,22,33,44,55,11,1,22,33] c1 = collections.Counter(li) print c1 Counter({33: 2, 11: 2, 22: 2, 1: 1, 44: 1, 55: 1}) 有序字典 dic = {‘k1‘:123,‘k2‘:123,‘k3‘:12} dic1 = collections.OrderedDict() dic1[‘k1‘] = 1 dic1[‘k2‘] = 1 dic1[‘k3‘] = 1 {‘k3‘: 12, ‘k2‘: 123, ‘k1‘: 123} OrderedDict([(‘k1‘, 1), (‘k2‘, 1), (‘k3‘, 1)]) 默认字典 原生字典中dic{‘k1‘:None} if ‘k1‘ in dic.keys(): dic[‘k1‘].append(1) else: dic[‘k1‘] = [] 得到dic{‘k1‘:[]} 默认字典中 my_dic = collections.defaultdict(list) 就能得到 my_dic{‘k1‘:[]} 为字典中value设置一个默认类型可以是字典、列表、元组 可命名元组 #创建一个扩展的元组类,mytuple,除了元组本身的使用方法还扩展了自己定义的方法 mytuple = collections.namedtuple(‘mytuple‘,[‘x‘,‘y‘]) new = mytuple(1,2) print new print new.x print new.y mytuple(x=1, y=2) 1 2 双向队列 #双向队列 q = collections.deque() #右边添加 q.append(1) q.append(2) q.append(3) q.append(4) #左边添加 q.appendleft(5) #右边删除 q.pop() #左边删除 q.popleft()
时间: 2024-10-17 16:36:21