我有一些名字:["James", "John", "Krieg"]和一些颜色:["Red", "Green", "Blue", "Yellow"]。我想使用一些散列函数将名称映射到颜色:f(name) -> color。这种联系是幂等的。例如,如果在原始列表f(James) -> Red中,那么在我将名称或颜色添加到它们各自的列表中之后,f(James)仍然是Red。
示例:
列表状态1:
["James", "John", "Krieg"] and ["Red", "Green", "Blue", "Yellow"]:
f(James) -> Red
f(John) -> Yellow
f(Krieg) -> Yellow列表状态2:
["James", "John", "Krieg", "Sarah"] and ["Red", "Green", "Blue", "Yellow", "Black"]:
(added "Sarah" and "Black")
f(James) -> Red
f(John) -> Yellow
f(Krieg) -> Yellow
f(Sarah) -> Green散列函数的细节并不重要,只要它尝试一致性即可。我之所以有这个问题,是因为我有一个显示给用户的姓名列表,并且随着该列表的增长,我希望以前输入的姓名的颜色关联是相同的(以便用户保留姓名/颜色关联)。我意识到,如果我提前指定了颜色列表,这将不是问题。
所以现在只是出于好奇--有没有哈希函数不会随着输入/输出大小的增长而改变先前关联的值,而不是持久性?对于之前的混乱,我很抱歉。
发布于 2011-06-03 05:23:14
如果我理解您的问题,您想要一个对象,它将接受一个键列表和一个值列表(长度为任意长度或不长度),并返回一个字典,该字典始终具有相同的值,而不管添加了什么。
>>> class ListOMatic(object):
def __init__(self):
self.people = []
self.colors = []
def idpt(self, people=[], colors=[]):
for p in people:
if not p in self.people:
self.people.append(p)
for c in colors:
if not c in self.colors:
self.colors.append(c)
return dict(zip(self.people, self.colors))
>>> lom = ListOMatic()
>>> people = ['James', 'John', 'Krieg']
>>> colors = ['Red', 'Green', 'Blue', 'Yellow']
>>> # populate it with our initial values and show that we can pull values out.
>>> print (lom.idpt(people, colors))
{'James': 'Red', 'John': 'Green', 'Krieg': 'Blue'}
>>> print (lom.idpt())
{'James': 'Red', 'John': 'Green', 'Krieg': 'Blue'}
>>> print (lom.idpt()["James"])
Red
>>> # add some colors but no names.
>>> print (lom.idpt([],["Purple", "Mauve"]))
{'James': 'Red', 'John': 'Green', 'Krieg': 'Blue'}
>>> print (lom.idpt())
{'James': 'Red', 'John': 'Green', 'Krieg': 'Blue'}
>>> # add a name and show that it "picks up" the first available color
>>> print (lom.idpt(["Sarah"],[]))
{'Sarah': 'Yellow', 'James': 'Red', 'John': 'Green', 'Krieg': 'Blue'}
>>> print (lom.idpt(["Victor", "Charlie"],["Puce"]))
{'Sarah': 'Yellow', 'James': 'Red', 'Charlie': 'Mauve', 'John': 'Green', 'Krieg': 'Blue', 'Victor': 'Purple'}
>>> print (lom.idpt())
{'Sarah': 'Yellow', 'James': 'Red', 'Charlie': 'Mauve', 'John': 'Green', 'Krieg': 'Blue', 'Victor': 'Purple'}
>>> print (lom.idpt()["Sarah"])
Yellow
>>> 希望这就是你所说的“在飞行中”的意思。
https://stackoverflow.com/questions/6220144
复制相似问题