【问题标题】:Pulling an object out of a queue based on a data member根据数据成员将对象从队列中拉出
【发布时间】: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


【解决方案1】:

这种方法效果很好,毕竟不是那么笨拙。最大的不同可能是传递一个谓词,而不是将测试硬编码到下一条语句中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    相关资源
    最近更新 更多