有序字典(orderedDict)

orderdDict是对字典类型的补充,他记住了字典元素添加的顺序

例:
import
collections dic = collections.OrderedDict() dic['k1'] = 'v1' dic['k2'] = 'v2' dic['k3'] = 'v3' print(dic)

得:

OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])

 
把数据拿到最后
def move_to_end(self, key, last=True): '''Move an existing element to the end (or beginning if last==False). Raises KeyError if the element does not exist. When last=True, acts like a fast version of self[key]=self.pop(key). ''' link = self.__map[key] link_prev = link.prev link_next = link.next soft_link = link_next.prev link_prev.next = link_next link_next.prev = link_prev root = self.__root if last: last = root.prev link.prev = last link.next = root root.prev = soft_link last.next = link else: first = root.next link.prev = root link.next = first first.prev = soft_link root.next = link
例:
import
collections dic = collections.OrderedDict() dic['k1'] = 'v1' dic['k2'] = 'v2' dic['k3'] = 'v3' print(dic) dic.move_to_end('k1') print(dic)
得:

OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
OrderedDict([('k2', 'v2'), ('k3', 'v3'), ('k1', 'v1')])

import collections

dic = collections.OrderedDict()
dic['k1'] = "v1"
dic['k2'] = 'v2'
dic['k3'] = 'v3'

print(dic)

dic.popitem()#后进先出、栈就是按照这种顺序来的
print(dic)

ret = dic.pop('k2')#指定拿出
print(dic)

print(ret)#有返回值
import collections
dic = collections.OrderedDict()
#dic['k4'] = None
dic.setdefault('k4','666')#设置默认值
print(dic)

输出:
OrderedDict([('k4', '666')])
import collections
dic = collections.OrderedDict()
dic['k1'] = 'v1'
dic['k2'] = 'v2'
#dic['k4'] = None
#dic.setdefault('k4','666')#设置默认值
dic.update({'k1':'kw','k10':'v10'})#更新字典、没有加进去、有的话、改值
print(dic)

输出:
OrderedDict([('k1', 'kw'), ('k2', 'v2'), ('k10', 'v10')])

字典默认的时候循环、只输出key

默认字典:

import collections
dic ={'k1':[]}
collections.defaultdict(list)#默认字典、默认值就是list
dic['k1'].append('alex')
print(dic)

输出:

{'k1': ['alex']}

实例:

from
collections import defaultdict values = [11,22,33,44,55,66,77,88,99,90] my_dict = defaultdict(list) for value in values: if value >66: my_dict['k1'].append(value) else: my_dict['k2'].append(value) print(my_dict)

输出:
defaultdict(<class 'list'>, {'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99, 90]})

 可命名元组(nametuple)

根据nametuple可以创建一个包含tuple所有功能以及其他功能的类型

import collections
#创建类,defaultdict
MytupleClass = collections.namedtuple('MytupleClass',['x', 'y', 'z'])
print(help(MytupleClass))
obj = MytupleClass(11,22,33)
print(obj.x)
print(obj.y)
print(obj.z)

输出:

11
22
33

 双向队列:

 
#在后边一个一个添加
def append(self, *args, **kwargs): # real signature unknown """ Add an element to the right side of the deque. """ pass #往左边添加
def appendleft(self, *args, **kwargs): # real signature unknown """ Add an element to the left side of the deque. """ pass
#清空队列 def clear(self, *args, **kwargs): # real signature unknown """ Remove all elements from the deque. """ pass

#看看队列某个元素出现了多少次 def count(self, value): # real signature unknown; restored from __doc__ """ D.count(value) -> integer -- return number of occurrences of value """ return 0
import collections
#双向队列
d = collections.deque()
d.append('1')
d.appendleft('10')
d.appendleft('1')
print(d)
r = d.count('1')
print(r)
输出:

deque(['1', '10', '1'])
2


#扩展(多个元素一起放进去)

def extend(self, *args, **kwargs): # real signature unknown
        """ Extend the right side of the deque with elements from the iterable """
        pass
import collections
#双向队列
d = collections.deque()
d.append('1')
d.appendleft('10')
d.appendleft('1')
print(d)
r = d.count('1')
print(r)
d.extend(['yy','uu','ii'])#右边扩展
d.extendleft(['y1y','u1u','i1i'])#左边扩展
print(d)

输出:

deque(['1', '10', '1'])
2
deque(['i1i', 'u1u', 'y1y', '1', '10', '1', 'yy', 'uu', 'ii'])

    def extendleft(self, *args, **kwargs): # real signature unknown
        """ Extend the left side of the deque with elements from the iterable """
        pass


#从右边取值 def pop(self, *args, **kwargs): # real signature unknown """ Remove and return the rightmost element. """ pass

#从左边取值 def popleft(self, *args, **kwargs): # real signature unknown """ Remove and return the leftmost element. """ pass

#删除某些值 def remove(self, value): # real signature unknown; restored from __doc__ """ D.remove(value) -- remove first occurrence of value. """ pass
#反转 def reverse(self): # real signature unknown; restored from __doc__ """ D.reverse() -- reverse *IN PLACE* """ pass

#把后面的拿到前面 def rotate(self, *args, **kwargs): # real signature unknown """ Rotate the deque n steps to the right (default n=1). If n is negative, rotates left. """ pass
import collections
#双向队列
d = collections.deque()
d.append('1')
d.appendleft('10')
d.appendleft('1')
print(d)
r = d.count('1')
print(r)
d.extend(['yy','uu','ii'])#右边扩展
d.extendleft(['y1y','u1u','i1i'])#左边扩展
print(d)
d.rotate(1)
print(d)
d.rotate(5)
print(d)
输出:

deque(['1', '10', '1'])
2
deque(['i1i', 'u1u', 'y1y', '1', '10', '1', 'yy', 'uu', 'ii'])
deque(['ii', 'i1i', 'u1u', 'y1y', '1', '10', '1', 'yy', 'uu'])
deque(['1', '10', '1', 'yy', 'uu', 'ii', 'i1i', 'u1u', 'y1y'])

 



单向队列:

队列里元素的个数:
def qsize(self): '''Return the approximate size of the queue (not reliable!).''' with self.mutex: return self._qsize()
#和clear一样、清空
def empty(self): '''Return True if the queue is empty, False otherwise (not reliable!). This method is likely to be removed at some point. Use qsize() == 0 as a direct substitute, but be aware that either approach risks a race condition where a queue can grow before the result of empty() or qsize() can be used. To create code that needs to wait for all queued tasks to be completed, the preferred technique is to use the join() method. ''' with self.mutex: return not self._qsize()
#队列可以定义个数、是否填满了
def full(self): '''Return True if the queue is full, False otherwise (not reliable!). This method is likely to be removed at some point. Use qsize() >= n as a direct substitute, but be aware that either approach risks a race condition where a queue can shrink before the result of full() or qsize() can be used. ''' with self.mutex: return 0 < self.maxsize <= self._qsize()
#往里插入一条数据
def put(self, item, block=True, timeout=None): '''Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raises the Full exception if no free slot was available within that time. Otherwise ('block' is false), put an item on the queue if a free slot is immediately available, else raise the Full exception ('timeout' is ignored in that case). ''' with self.not_full: if self.maxsize > 0: if not block: if self._qsize() >= self.maxsize: raise Full elif timeout is None: while self._qsize() >= self.maxsize: self.not_full.wait() elif timeout < 0: raise ValueError("'timeout' must be a non-negative number") else: endtime = time() + timeout while self._qsize() >= self.maxsize: remaining = endtime - time() if remaining <= 0.0: raise Full self.not_full.wait(remaining) self._put(item) self.unfinished_tasks += 1 self.not_empty.notify()
#拿出
def get(self, block=True, timeout=None): '''Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raises the Empty exception if no item was available within that time. Otherwise ('block' is false), return an item if one is immediately available, else raise the Empty exception ('timeout' is ignored in that case). ''' with self.not_empty: if not block: if not self._qsize(): raise Empty elif timeout is None: while not self._qsize(): self.not_empty.wait() elif timeout < 0: raise ValueError("'timeout' must be a non-negative number") else: endtime = time() + timeout while not self._qsize(): remaining = endtime - time() if remaining <= 0.0: raise Empty self.not_empty.wait(remaining) item = self._get() self.not_full.notify() return item
import queue

q = queue.Queue()#创建一个单项队列
q.put('123')
q.put('789')
print(q.qsize())
print(q.get())#先进先出

输出:

2
123

先进先出

原文地址:https://www.cnblogs.com/mrzuo/p/7096913.html