python 库中的 FIFO class?

FIFO class in python library?

下面是 Python 中 FIFO 的简单实现。我的问题是在维护包中是否已经存在任何等价物,尤其是标准库中的任何东西,因为这似乎是一件相当普遍的事情。

功能:您必须能够像列表一样append对其进行迭代,但是当迭代产生一个元素时,必须销毁对该元素的内部引用。

这是我想用它做什么的例子:

f = Fifo()

# append to it

for i in range(5):
    f.append(i)
print("length:", len(f))

# iterate over it, including appending while iterating

for i in f:
    print("item:", i)
    if i == 3:
        f.append("something")
print("all for now")

# iterate again (maybe we didn't previously iterate fully,
# or, as in this example, appended some more items afterwards)

f.append("another thing")
f.append("and another thing")
print("length:", len(f))
for i in f:
    print("item:", i)

给予:

length: 5
item: 0
item: 1
item: 2
item: 3
item: 4
item: something
all for now
length: 2
item: another thing
item: and another thing

这是我的实现。 (这使用字典。稍微简单但效率较低的替代方案在内部使用列表。)

class Fifo:

    def __init__(self):
        self._d = {}
        self._cur = 0  # next key to pop

    def __len__(self):
        return len(self._d)

    def append(self, v):
        self._d[self._cur + len(self._d)] = v

    def __next__(self):
        if self._d:
            v = self._d.pop(self._cur)
            self._cur += 1
            return v
        else:
            raise StopIteration

    def __iter__(self):
        return self

您可以使用 Queue

queue = Queue()

queue.put(0)
queue.put(1)

while not queue.empty():
  print(queue.get())

作为 FIFO 数据结构,您接下来可以使用:

  • list - append()pop() 函数被使用。
  • collections.deque - append()popleft()
  • Queue.queue - get()put()等,适合多线程编程

你在找这个吗?

from queue import SimpleQueue


class Fifo(SimpleQueue):
    def __iter__(self):
        return self

    def __len__(self):
        return self.qsize()

    def __next__(self):
        if not self.empty():
            return self.get()
        raise StopIteration

fifo = Fifo()
fifo.put(10)
fifo.put(20)
for item in fifo:
    print(item)

print(f'fifo size after iteration {len(fifo)}')

输出

10
20
fifo size after iteration 0