Python 是否有可排序和可搜索的数据结构?
我正在使用 python 来管理要处理的字符串队列。它有几个要求:
- 每个字符串都与一个优先级匹配,并且仅根据该值进行处理。
- 可以动态地将字符串添加到该队列中,但队列中不允许有重复的字符串。如果提交了重复项,则必须对其进行识别并忽略。
那么有没有任何Python数据类型可以允许这样的事情呢?还是我必须自己写?
如果没有本地结构,我会考虑维护两种结构。
只要这些已存储不失去同步应该可以解决问题。
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.
- A heapq which will maintain the strings and their priority
- 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这听起来是一个合理的方法。我会使用
set
而不是list
因为它具有更有效的成员资格检查,并且您不需要维护顺序(因为您在 heapq 中执行此操作)That sounds like a reasonable approach. I would use a
set
instead of alist
since it has more efficient membership checking and you don't need to maintain order (since you do it in the heapq)一本有序的字典可能会有所帮助。
请参阅此页面(有序字典),其中状态:
An ordered dictionary may be of help.
See this page (an ordered dictionary) where it states: