要求:我有一大组独特的字符串。我需要为每个人分配一个唯一的 int id。之后,从字符串获取 id 或从 id 获取字符串应该足够高效(内存和速度)。
如果在c/c++中,可以将这些字符串存储在哈希表中(例如,const char * 的数组),并将表中字符串的索引指定为id。
是否可以在 python 中做同样的事情或其他解决方案?否则我需要维护两个将字符串映射到 ids 的字典,反之亦然。
更新:该集合已卡住,无需更改。
最佳答案
如果只有string -> id
就足够了,只需使用hash
功能:
In [2]: hash( 'hello' )
Out[2]: 840651671246116861
In [3]: hash( 'helloo' )
Out[3]: -827725961091893887
如果您需要两种方式,正如 @njzk2 建议的那样:
values = {hash(value): value for value in string_list}
# from id -> string:
values[id]
# from string -> id:
hash(string)
如果您对哈希冲突很谨慎,并且您的数据是静态的,您可以检查是否存在任何冲突:
hashes = set()
for value in string_list:
hashed = hash(value)
if hashed in hashes:
print('at least one collision in hashing')
break
hashes.add(hashed)
print('no collisions at hashing')
如果发生任何冲突(这种情况不太可能发生),您可以执行以下操作:
myDict1 = {} # string --> id dictonary
myDict2 = {} # id --> string dictionary
counter = 0
for value in string_list:
myDict1[value] = counter
myDict2[counter] = value
counter += 1
关于python - 在 python 中维护一组 id <-> 字符串关系的有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31307770/