繁体   English   中英

字典成为字典Python中的键

[英]Dictionary be a Key in a Dictionary Python

我想要一种O(1)方法来检查自己是否处于状态。 问题在于状态是由地图上几个zoombinis的位置定义的。 Zoombini = {(1,1):0,(2,2):1,(3,3):3} {位置:Zoombini ID}我正在使用广度优先搜索,并将此位置词典推入我的队列。

dirs = [goNorth, goSouth, goWest, goEast] ## List of functions
zoom = {}
boulders = {}
visited = {} ## {(zoom{}): [{0,1,2},{int}]}
             ## {Map: [color, distance] 0 = white, 1 = gray, 2 = black
n = len(abyss)
for i in xrange(n):
    for j in xrange(n):
        if (abyss[i][j] == 'X'):
            boulders[(i,j)] = True
        elif (isInt(abyss[i][j])):
            zoom[(i,j)] = int(abyss[i][j])      ## invariant only 1 zomb can have this position
        elif (abyss[i][j] == '*'):
              exit = (i, j)
sQueue = Queue.Queue()
zombnum = 0
done = False
distance = 0
sQueue.put(zoom)
while not(sQueue.empty()):
    currZomMap = sQueue.get()
    for zom in currZomMap.iterkeys(): ## zoom {(i,j): 0}
        if not(zom == exit):
            z = currZomMap[zom]
            for fx in dirs: ## list of functions that returns resulting coordinate of going in some direction
                newPos = fx(zom)
                newZomMap = currZomMap.copy()
                del(newZomMap[zom]) ## Delete the old position
                newZomMap[newPos] = z ## Insert new Position
                if not(visited.has_key(newZomMap)):
                    sQueue.put(newZomMap)

我的实现尚未完成,但是我需要一种更好的方法来检查是否已经访问过一个状态。 我可以创建一个从字典中创建整数散列的函数,但我认为我无法高效地执行此操作。 时间也是一个问题。 我怎样才能做到最好?

与其构造一些易碎的自定义哈希函数,不如说我只使用frozenset

>>> Z = {(1,1): 0, (2,2):1, (3,3):3}
>>> hash(Z)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> frozenset(Z.items())
frozenset([((2, 2), 1), ((1, 1), 0), ((3, 3), 3)])
>>> hash(frozenset(Z.items()))
-4860320417062922210

冻结集可以存储在集合和字典中,没有任何问题。 您还可以使用从Z.items()构建的元组,但必须确保始终以规范格式存储该元组(例如,首先对其进行排序)。

Python不允许使用可变键,因此我最终创建了一个对字典进行哈希处理的函数。

编辑 -

def hashthatshit(dictionary):
result = 0
i =0
for key in dictionary.iterkeys():
    x = key[0]
    y = key[1]
    result+=x*10**i+y*10**(i+1)+\
             10**(i+2)*dictionary[key]
    i+=3
return result

我使用了特定于实现的代码,这就是为什么我最初不包含它的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM