如何使用 Python 为相同的输入 ID 生成唯一 ID?
How to generate a unique id for same input id using Python?
我有一个 ID 列表,我想使用 Python.
为列表中的每个 ID 显示一个假 ID
我使用了 uuid1() 但是当我的列表中有重复的 id 时,程序停止并且不会为相同的输入 id 生成相同的随机 id。
print uuid.uuid1(data['user']['id']).int>>64
从python uuid doc开始,uuid1依赖于当前时间。
您可以使用 uuid3 通过重用相同的命名空间为相同的输入获得可重现的 uuid:
namespace = uuid.uuid4()
...
print uuid.uuid3(namespace, "1")
你可以散列你的 id :
import hashlib
id = 12
hashlib.sha256(str(id).encode()).hexdigest() # with python2.x you don't need to encode()
# => '6b51d431df5d7f141cbececcf79edf3dd861c3b4069f0b11661a3eefacbba918'
不过您必须将对应关系存储在某处,因为无法从哈希中检索 ID。
我有一个 ID 列表,我想使用 Python.
为列表中的每个 ID 显示一个假 ID我使用了 uuid1() 但是当我的列表中有重复的 id 时,程序停止并且不会为相同的输入 id 生成相同的随机 id。
print uuid.uuid1(data['user']['id']).int>>64
从python uuid doc开始,uuid1依赖于当前时间。
您可以使用 uuid3 通过重用相同的命名空间为相同的输入获得可重现的 uuid:
namespace = uuid.uuid4()
...
print uuid.uuid3(namespace, "1")
你可以散列你的 id :
import hashlib
id = 12
hashlib.sha256(str(id).encode()).hexdigest() # with python2.x you don't need to encode()
# => '6b51d431df5d7f141cbececcf79edf3dd861c3b4069f0b11661a3eefacbba918'
不过您必须将对应关系存储在某处,因为无法从哈希中检索 ID。