分类: Python/Ruby
2016-06-19 10:47:45
1、计数器:
import collections c1=collections.Counter("yyzzfjkasfafa") print(c1) #Counter({'a': 3, 'f': 3, 'y': 2, 'z': 2, 'k': 1, 'j': 1, 's': 1})
l1=[11,22,33,44,55,22,44,11,66,22]
c1=collections.Counter(l1)
print(c1)
#Counter({22: 3, 11: 2, 44: 2, 33: 1, 66: 1, 55: 1})c1.update(c1) print(c1) #Counter({22: 6, 11: 4, 44: 4, 33: 2, 66: 2, 55: 2}) for i in c1.elements(): print(i) """ 33 33 66 66 .... """2、有序字典:(字典内部维护了一个列表,把字典的key都存进列表)(使用和字典一样使用)import collections o1=collections.OrderedDict() o1['key1']=1 o1['key2']=2 print(o1) #OrderedDict([('key1', 1), ('key2', 2)]) print(o1.keys()) #['key1', 'key2'] print(o1.values()) #[1, 2]3、默认字典:import collectionsdic={'k1':None}dic['k1'].append(1) X """dic.['k1'] ===> None ,None没有appendf方法"""dic={}if 'k1' in dic.keys():dic['k1'].append(1)else:dic['k1']=[1,]my_dic=collections.defaultdict(list) "相当于创建了个my_dic={'k':[]}"my_dic['k1'].append(1)===> my_dic={}my_dic['k1']=[]dic['k1'].append(1)二、可命名元祖:(一般用于坐标)
1、创建类2、使用创建的类创建对象3、使用对象import collectionsMytuple=collections.namedtuple("Mytuple",['x','y'])new=Mytuple(1,2)# Mytuple(x=1,y=2)new.x# 1new.y# 2三、双向队列
import collectionsq=collections.deque()q.append(1)q.append(2)q.append(3)q.pop()q.popleft()"""单向队列:import Queueq=Queue.Queueq.put(1)q.put(2)q.get()"""