python中的元组匹配字典键(元组) [英] partial match dictionary key(of tuples) in python
本文介绍了python中的元组匹配字典键(元组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字典将3tuple映射到3tuple,其中key-tuple有一些共同的元素
I have a dictionary that maps 3tuple to 3tuple where key-tuples have some element in common
dict= { (a,b,c):(1,2,3),
(a,b,d):tuple1,
(a,e,b):tuple,
.
(f,g,h):tuple3,
.
.
.
tuple:tuple
}
现在我如何找到匹配的值到(a,b, anyX )在字典 ie(1:2:3)和tuple1
now how can I find the values that match to (a,b,anyX) in a dictionary ie (1:2:3) and tuple1
这是计算机生成和非常大的,因此,需要努力确定anyX。
this is computer generated and very large thus, it takes effort to determine anyX.
所以,有什么好的方法我可以做到这一点?
so, any good ways I can do this?
编辑:(f,g,*),(f,*,g)到tuple3的部分匹配也将是有帮助的,但不是必需的。
edit:partial matching of (f,g,*),(f, *,g) to tuple3 will also be helpful but not necessary.
推荐答案
c> all 和 zip
:
>>> from itertools import permutations
>>> import random
#create a sample dict
>>> dic = {k:random.randint(1, 1000) for k in permutations('abcde', 3)}
def partial_match(key, d):
for k, v in d.iteritems():
if all(k1 == k2 or k2 is None for k1, k2 in zip(k, key)):
yield v
...
>>> list(partial_match(('a', 'b', None), dic))
[541, 470, 734]
>>> list(partial_match(('a', None, 'b'), dic))
[460, 966, 45]
#Answer check
>>> [dic[('a', 'b', x)] for x in 'cde']
[541, 734, 470]
>>> [dic[('a', x, 'b')] for x in 'cde']
[966, 460, 45]
这篇关于python中的元组匹配字典键(元组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文