我有一个带有列表的字典,我的目标是将查询列表与字典匹配,并且匹配的术语显示相交的值。例如
dict= [(this, ['1']), (word, ['1', '2']), (search, ['2'])]
searchedQuery = [this, word]
output = 1
有人能告诉我实施这种技术的最简单方法,我正在考虑使用这种方法
for key in dict.keys():
...get values
...intersect values
答案 0 :(得分:2)
像这样:
>>> d
[('this', ['1']), ('word', ['1', '2']), ('search', ['2'])]
>>> set.intersection(*[set(v) for k,v in d if k in searchedQuery])
set(['1'])
说明:
for k,v in d if k in searchedQuery
枚举d
中包含您想要的键[set(v) ...]
制作值集*
解压缩列表,以便我们传递给set.intersection
set.intersection
为您提供了交集。 旁白:
dict
。 dict
用于您自己的变量名称被认为不是一个好主意(但我们明白您的意思)。答案 1 :(得分:1)
这个怎么样:
>>> dic = dict([('this', ['1']), ('word', ['1', '2']), ('search', ['2'])])
>>> searchedQuery = ['this', 'word']
>>> [y for x,y in dic.items() if x in searchedQuery]
[['1'], ['1', '2']]
>>>
答案 2 :(得分:1)
你可以做同样的事情。但是在进入它之前,你需要了解的东西很少。
Python中的字典,看起来像这样
d = {'this': ['1'], 'search': ['2'], 'word': ['1', '2']}
因此,为了获得您以字典形式呈现的数据,您需要执行类似的操作
d = [('this', ['1']), ('word', ['1', '2']), ('search', ['2'])]
print dict(item for item in d)
然后你可以从字典中获取对应于searchedQuery
的值,最后像这样设置交集
print set.intersection(*[set(d.get(item, {})) for item in searchedQuery])
# set(['1'])