Skip to main content
 首页 » 编程设计

python之在 python 中维护一组 id -> 字符串关系的有效方法

2024年10月24日35kerrycode

要求:我有一大组独特的字符串。我需要为他们每个人分配一个唯一的 int id。之后,从字符串获取 id 或从 id 获取字符串应该足够有效(内存和速度)。

如果在c/c++中,可以将这些字符串存储在哈希表中(例如const char *的数组),并将表中字符串的索引指定为id。

是否可以在 python 中做同样的事情或其他解决方案?否则,我需要维护两个将字符串映射到 id 的 dict 和 vice vasa。

更新:集合已卡住,无需更改。

请您参考如下方法:

如果只有 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