partial match dictionary key(of tuples) in python

后端 未结 4 1347
长发绾君心
长发绾君心 2020-12-09 13:00

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):         


        
4条回答
  •  误落风尘
    2020-12-09 13:09

    There might be other ways, but assuming you just need to do a single search (in other words there might be ways to build better data structures for repeated searching): (Note that this handles arbitrary lengthed tuple's with the '*' in multiple possible locations)

    def match(tup,target):
       if len(tup) != len(target):
          return False
       for i in xrange(len(tup)):
          if target[i] != "*" and tup[i] != target[i]:
             return False
       return True
    
    def get_tuples(mydict,target):
       keys = filter(lambda x: match(x,target),mydict.keys())
       return [mydict[key] for key in keys]
    
    #example:
    dict= { (1,3,5):(1,2,3),
            (1,3,6):(1,5,7),
            (1,2,5):(1,4,5),
           }
    print get_tuples(dict,(1,3,'*'))
    

    .

提交回复
热议问题