python字典的键可以是元组吗,python中的元组匹配字典键(元组)

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

}

now how can I find the values that match to (a,b,anyX) in a dictionary ie (1:2:3) and tuple1

this is computer generated and very large thus, it takes effort to determine anyX.

so, any good ways I can do this?

edit:partial matching of (f,g,*),(f, *,g) to tuple3 will also be helpful but not necessary.

解决方案

Lets say if you're passing None for the missing keys then you can use all and 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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值