tMC*_*tMC 6 python string buffer
Python 有用于字符串 FIFO 缓冲的数据类型吗?我创建了一些东西(如下),但怀疑我正在重新发明轮子。
class Buffer(list):
def __init__(self):
super(Buffer, self).__init__()
def put(self, nlmsg):
for c in nlmsg: self.append(c)
def peek(self, number):
return "".join( [self[i] for i in range(number)] )
def get(self, number):
return "".join( [self.pop(0) for i in range(number)] )
Run Code Online (Sandbox Code Playgroud)
使用示例:
>>> buf = Buffer()
>>> buf.put('abcdefg')
>>> buf
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> buf.peek(4)
'abcd'
>>> buf
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> buf.get(5)
'abcde'
>>> buf
['f', 'g']
Run Code Online (Sandbox Code Playgroud)
我看了看,Queue但是当添加一个 str 时,我必须手动分割每个字节,否则整个 str 将成为队列中的一个项目。那里已经有类似的东西了吗?
使用collections.deque它的实现方式如下:
from collections import deque
class Buffer(deque):
def put(self, iterable):
for i in iterable:
self.append(i)
def peek(self, how_many):
return ''.join([self[i] for i in xrange(how_many)])
def get(self, how_many):
return ''.join([self.popleft() for _ in xrange(how_many)])
buf = Buffer()
buf.put('abcdefg')
print buf
print buf.peek(4)
print buf
print buf.get(5)
print buf
Run Code Online (Sandbox Code Playgroud)
输出示例:
deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
abcd
deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
abcde
deque(['f', 'g'])
Run Code Online (Sandbox Code Playgroud)