繁体   English   中英

如何在python中使用自定义类实现优先级队列?

[英]How to implement priority queue with a custom class in python?

我来自java背景,我需要这样的东西

public class Item implements Comparable<Item> {

    int score;
    ArrayList<Integer> arr;

    @Override
    public int compareTo(Item o2) {
        return score != o2.score ? score - o2.score : arr.size() - o2.arr.size();
    }


    public static void main(String[] args) {
        PriorityQueue<Item> p = new PriorityQueue<Item>();

    }
}

所以我有一个有两个变量,分数和列表的类。 也有自然排序的计算。

有人可以告诉我如何做python? heapq对我不起作用,因为我的分数函数根据两个变量而不是一个变量来检查分数。

你很幸运,因为实现已经存在

确保遵循条目的常规结构,并使用表单元组(priorities_tuple, entry)将优先级附加到插入队列的所有条目。

一个例子:

import Queue
import random
pq = Queue.PriorityQueue()
todos = ["eat", "sleep", "python"]
# obvously replace random with your 
todos_with_priorities = [((random.random(),), e) for e in todos]
for e in todos:
    pq.put(e)

像这样消耗队列:

priorities, item = pq.get()

为了形成越来越复杂的优先级,为元组结构添加更多成员。 在你的情况下,元组应该是这样的: ((e.score, len(e.arr)), e)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM