简体   繁体   English

如何使用 Python 为相同的输入 ID 生成唯一 ID?

[英]How to generate a unique id for same input id using Python?

I have a list of ids and I want to display a fake id for each id in my list using Python.我有一个 ID 列表,我想使用 Python 为列表中的每个 ID 显示一个假 ID。

I used the uuid1() but when there is a duplicated id in my list the program stop and don't generate the same random id for same input id.我使用了 uuid1() 但是当我的列表中有重复的 id 时,程序会停止并且不会为相同的输入 id 生成相同的随机 id。

 print uuid.uuid1(data['user']['id']).int>>64

from python uuid doc , uuid1 is dependent on current time.来自python uuid doc , uuid1 取决于当前时间。

You could use uuid3 to have a reproducible uuid for the same input, by reusing the same namespace:通过重用相同的命名空间,您可以使用uuid3为相同的输入生成可重现的 uuid:

namespace = uuid.uuid4()
...
print uuid.uuid3(namespace, "1")

You could just hash your id :你可以散列你的 id :

import hashlib
id = 12
hashlib.sha256(str(id).encode()).hexdigest() # with python2.x you don't need to encode()
# => '6b51d431df5d7f141cbececcf79edf3dd861c3b4069f0b11661a3eefacbba918'

You'll have to store the correspondance somewhere though, because there is no way to retrieve the id from a hash.但是,您必须将对应关系存储在某处,因为无法从散列中检索 id。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM