【发布时间】:2023-03-18 10:22:01
【问题描述】:
我需要扩展队列,以便我可以根据对象的数据成员之一的值从队列中取出一个对象。
我已经解决了这样的问题,我想知道我是不是很密集。我真的需要进行列表转换才能找到对象吗?
class Datum:
def __init__(self, id):
self.id = id
def __str__(self):
return str(self.id)
class PluckQueue(Queue):
def pluck(self, id):
with self.not_empty:
plucked = None
while plucked is None:
pluck_list = list(self.queue)
try:
plucked = next(xx for xx in pluck_list if xx.id == id )
except StopIteration:
plucked = None
if plucked is None:
self.not_empty.wait()
else:
index = pluck_list.index(plucked)
self.queue.remove(pluck_list[index])
return plucked
def __str__(self):
return str([str(xx) for xx in self.queue])
pq = PluckQueue()
pq.put(Datum('a'))
pq.put(Datum('b'))
pq.put(Datum('c'))
plucked = pq.pluck('b')
print(plucked)
print(pq)
这给出了结果:
b
['a', 'c']
我错过了一种更简单的方法吗?
【问题讨论】:
-
似乎违背了队列的目的,你不觉得吗?如果可能的“类别”数量不是太多,您可以使用子队列吗?
-
我们不去解释原因。
标签: python python-3.x queue