Python 是否有可排序和可搜索的数据结构?

发布于 2024-11-09 19:53:27 字数 504 浏览 2 评论 0原文

我正在使用 python 来管理要处理的字符串队列。它有几个要求:

  • 每个字符串都与一个优先级匹配,并且仅根据该值进行处理。
  • 可以动态地将字符串添加到该队列中,但队列中不允许有重复的字符串。如果提交了重复项,则必须对其进行识别并忽略。

那么有没有任何Python数据类型可以允许这样的事情呢?还是我必须自己写?

如果没有本地结构,我会考虑维护两种结构。

  1. A heapq 将维护字符串及其优先级
  2. A list 维护字符串的哈希值,以检查字符串是否已存储,

只要这些已存储不失去同步应该可以解决问题。

I'm using python to manage a queue of strings to process. It has a couple of requirments:

  • Each string is matched to a priority and is processed based solely on that value.
  • Strings can be added to this queue dynamically but no duplicate Strings are allowed in the queue. If a duplicate is submitted then it must be identified and ignored.

So is there any python datatype that will allow something like this? Or do I have to write my own?

If there isn't a native one then, I'm thinking of maintaining two structures.

  1. A heapq which will maintain the strings and their priority
  2. A list which maintains a hash of the strings to check whether the string is already stored

As long as these do not fall out of sync it should solve the problem.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

若相惜即相离 2024-11-16 19:53:27

这听起来是一个合理的方法。我会使用 set 而不是 list 因为它具有更有效的成员资格检查,并且您不需要维护顺序(因为您在 heapq 中执行此操作)

That sounds like a reasonable approach. I would use a set instead of a list since it has more efficient membership checking and you don't need to maintain order (since you do it in the heapq)

清风无影 2024-11-16 19:53:27

一本有序的字典可能会有所帮助。

请参阅此页面(有序字典),其中状态:

有序字典按插入顺序保存键。这有时称为创建的订单字典。

字典有潜在的用例,可以保持键的顺序,但顺序是基于其他标准的。

您可以使用setkeys方法自由更改顺序,但您可能更喜欢使用这些不同标准的字典。例如,您可能需要一个字典,按照上次访问的键的顺序保存键。

An ordered dictionary may be of help.

See this page (an ordered dictionary) where it states:

The ordered dictionary keeps keys in insertion order. This is sometimes called a created order dictionary.

There are potential use cases for dictionaries that keep their keys in order, but the ordering being based on other criteria.

You are free to change the order using the setkeys method, but you may prefer a dictionary that used these different criteria. For example you might need a dictionary that kept keys in order of the last accessed key.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文