Python 如何匹配列表中的键并找到相交的值?
我有一个带有列表的字典,我的目标是根据字典匹配查询列表,匹配的术语显示相交的值。比如说Python 如何匹配列表中的键并找到相交的值?,python,string,dictionary,set,Python,String,Dictionary,Set,我有一个带有列表的字典,我的目标是根据字典匹配查询列表,匹配的术语显示相交的值。比如说 dict= [(this, ['1']), (word, ['1', '2']), (search, ['2'])] searchedQuery = [this, word] output = 1 有人能告诉我实现这种技术的最简单方法吗?我正在考虑使用这种方法 for key in dict.keys(): ...get values ...intersect value
dict= [(this, ['1']), (word, ['1', '2']), (search, ['2'])]
searchedQuery = [this, word]
output = 1
有人能告诉我实现这种技术的最简单方法吗?我正在考虑使用这种方法
for key in dict.keys():
...get values
...intersect values
这个怎么样:
>>> 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']]
>>>
像这样:
>>> d
[('this', ['1']), ('word', ['1', '2']), ('search', ['2'])]
>>> set.intersection(*[set(v) for k,v in d if k in searchedQuery])
set(['1'])
说明:
枚举对于k,如果searchedQuery中的k
中具有所需密钥的对d
生成一组值[set(v)…]
- 列表前面的
解压列表,以便我们可以传递到*
集合。交叉点
为您提供交叉点李>set.intersection
- 正如在另一个答案中提到的,配对列表实际上并不是一个
李>dict
- 使用
作为您自己的变量名被认为不是一个好主意(但我们明白您的意思)dict
- 你也可以这样做。但是,在开始之前,你需要了解的事情很少
Python中的字典,看起来像这样
d = {'this': ['1'], 'search': ['2'], 'word': ['1', '2']}
d = [('this', ['1']), ('word', ['1', '2']), ('search', ['2'])]
print dict(item for item in d)
print set.intersection(*[set(d.get(item, {})) for item in searchedQuery])
# set(['1'])
因此,为了获得以字典形式呈现的数据,您需要执行以下操作
d = {'this': ['1'], 'search': ['2'], 'word': ['1', '2']}
d = [('this', ['1']), ('word', ['1', '2']), ('search', ['2'])]
print dict(item for item in d)
print set.intersection(*[set(d.get(item, {})) for item in searchedQuery])
# set(['1'])
然后,您可以从字典中获取与searchedQuery
相对应的值,最后执行如下设置交集
d = {'this': ['1'], 'search': ['2'], 'word': ['1', '2']}
d = [('this', ['1']), ('word', ['1', '2']), ('search', ['2'])]
print dict(item for item in d)
print set.intersection(*[set(d.get(item, {})) for item in searchedQuery])
# set(['1'])