在Python中相交两个字典

编程入门 行业动态 更新时间:2024-10-24 01:50:55
本文介绍了在Python中相交两个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在通过一个倒排的索引来搜索一个搜索程序。索引本身是一个字典,其键是术语,其值本身是短文档的字典,ID号作为键,其文本内容作为值。

为了执行两个术语的和搜索,我需要与他们的贴子列表(词典)相交。什么是明确的(不一定是过分聪明的)在Python中这样做?我开始尝试了很多的方式与 iter :

p1 = index [term1] p2 = index [term2] i1 = iter(p1) i2 = iter(p2) while ...#不确定' != end'语法在这种情况下 ...

解决方案

您可以轻松计算交集,从而创建密钥集,并将其用于交集:

keys_a = set(dict_a.keys()) keys_b = set(dict_b.keys()) intersection = keys_a& keys_b#'&'运算符用于集合交集

I am working on a search program over an inverted index. The index itself is a dictionary whose keys are terms and whose values are themselves dictionaries of short documents, with ID numbers as keys and their text content as values.

To perform an 'AND' search for two terms, I thus need to intersect their postings lists (dictionaries). What is a clear (not necessarily overly clever) way to do this in Python? I started out by trying it the long way with iter:

p1 = index[term1] p2 = index[term2] i1 = iter(p1) i2 = iter(p2) while ... # not sure of the 'iter != end 'syntax in this case ...

解决方案

You can easily calculate the intersection of sets, so create sets from the keys and use them for the intersection:

keys_a = set(dict_a.keys()) keys_b = set(dict_b.keys()) intersection = keys_a & keys_b # '&' operator is used for set intersection

更多推荐

在Python中相交两个字典

本文发布于:2023-11-29 08:41:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645900.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   两个   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!