我想在 python 中生成 10 位唯一标识。我尝试了以下方法,但没有人成功
我们有没有合适的系统来生成 10 位唯一 ID?
尝试使用 hashlib 模块这样:
import hashlib
import random
def generate_id():
# Generate a random number
random_num = str(random.randint(0, 99999999)).encode()
# Generate a SHA-256 hash of the random number.
hash_obj = hashlib.sha256(random_num)
hex_digit = hash_obj.hexdigest()
return hex_digit[:10]
您可以生成具有唯一值(例如当前时间和随机数)的 SHA-1 哈希。然后,可以提取hash的十六进制值的前10个字符,得到10位数字。
导入哈希库 随机导入 导入时间
def generate_unique_id():
# Generate a unique value based on the current time and a random number
unique_value = str(time.time()) + str(random.randint(0, 9999999999))
# Hash the unique value using SHA-1
sha1 = hashlib.sha1(unique_value.encode('utf-8'))
# Extract the first 10 characters of the hexadecimal representation of the hash
unique_id = sha1.hexdigest()[:10]
return unique_id
请注意,这种方法应该生成具有低碰撞概率的唯一 ID,但 不能保证没有碰撞。特别是,如果短时间内产生的唯一值的个数超过哈希函数的输出空间,就可能发生碰撞。