Python MD5哈希后,取模,获取随机index
基本逻辑:
输入字符串,获取md5码,字符串形式获取末尾的两个16进制字符,然后使用int(xx,16)获取对应的[0,255]的值,取模index_size获得[0,index_size]对应的随机索引;
- Python2:
引入hashlib包:
import hashlib
1 def get_index(key): 2 md5 = hashlib.md5() 3 md5.update(key) 4 m = md5.hexdigest() 5 map_key = str(m)[-2:] 6 index = int(map_key,16) % 4 7 return index
- Python3:
引入包方式有变化;
1 from hashlib import md5 2 3 def get_index(key): 4 m = md5(key.encode("utf8")).hexdigest() 5 map_key = str(m)[-2:] 6 index = int(map_key, 16) % 4 7 return index
其他的写法:
m = md5(bytes(key, 'utf8')).digest()