在Python中进行配对查找的良好数据结构是什么?
由 paigh-key 我的意思是两个键,作为一个映射到单个值的一对。
F.EX我可以使用一组字符串作为键,我可以通过迭代搜索,尽管我想知道它是一种更好的方法来构造数据并根据一个或两个键之一找到对。
d = {
{"a", "b"}: "a-b relationship",
{"c", "d"}: "c-d relationship",
{"e", "f"}: "e-f relationship"
}
# single key
query = "a"
match = [v for k, v in d.items() if query in k]
# both keys
query = {"a", "b"}
match = [v for k, v in d.items() if query == k]
By pair-key I mean two keys as a pair mapped to a single value.
F.ex I could use a set of strings as keys, and i could search by iterating, though I’m wondering it there’s a better way to structure the data and find pairs based on either one of or both the keys.
d = {
{"a", "b"}: "a-b relationship",
{"c", "d"}: "c-d relationship",
{"e", "f"}: "e-f relationship"
}
# single key
query = "a"
match = [v for k, v in d.items() if query in k]
# both keys
query = {"a", "b"}
match = [v for k, v in d.items() if query == k]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的版本将仅使用 >作为键:
但是您也可能想尝试自己制作自己的
dict
类似于collections.abc
:然后,您可以将类用于两个目的:
collections.abc
a list of which methods you have to override for each abstract base class (abc) it provides您还需要添加其他便利方法,例如
__ epr __
和/或__ str __
,如果您将其用作公共面向公共的类。注意:我使用了一个单独的内部
dict
和的
dict> dict
的dict ,用于。这使单个查找的速度更快,但要付出少量的额外内存使用,并使项目设置较慢。调整您的用例。 =)The simplest version would be just using
frozenset
as keys:But you may also want to try making your own
dict
-like class withcollections.abc
:You can then use your class for both purposes:
collections.abc
has a list of which methods you have to override for each abstract base class (abc) it provides near the top of the documentation linked above.You'll also want to add other convenience methods like
__repr__
and/or__str__
if you use this as a public-facing class.Note: I used a separate internal
dict
anddict
ofdict
for pairs and single references. That makes single lookups much faster, but at the cost of a small extra memory use and making item setting a little slower. Adjust to your use case. =)这是一个建议,编写您的
addKeypair
函数以覆盖d [(a,b)] = v
的行为。Here is a suggestion, writing your
addKeyPair
function to override the behaviour ofd[(a, b)] = v
.