Python 生成短8位唯一id實戰教程
阿新 • • 發佈:2021-01-14
測試環境:
Win10
Python 3.5.4
實現思路
利用62個可列印字元,通過隨機生成32位UUID,由於UUID都為十六進位制,所以將UUID分成8組,每4個為一組,然後通過模62(字元0-9,a-z,A-Z總數量62個字元)操作,結果作為索引取出字元,這樣重複率大大降低,實踐測試,執行20000000次,僅出現2個重複id(僅測試過一次)。
當然,這樣還達不到唯一id,因為還是有重複的。解決方法呢,可以考慮結合資料庫、或者其它儲存來實現,以結合資料庫為例,我們可以新建一張資料庫表,並給表設定一個id欄位,並且設定為主鍵、或者增加唯一約束,每次獲取8 id後,往表裡插入一條資料,如果可以成功插入,說明不重複,否則說明是重複id,再次嘗試獲取。
核心程式碼
#!/usr/bin/env python # -*- coding:utf-8 -*- ''' @CreateTime: 2020/07/14 11:04 @Author : shouke ''' import uuid array = [ "0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z" ] def get_short_id(): id = str(uuid.uuid4()).replace("-",'') # 注意這裡需要用uuid4 buffer = [] for i in range(0,8): start = i * 4 end = i * 4 + 4 val = int(id[start:end],16) buffer.append(array[val % 62]) return "".join(buffer)
測試驗證
id_set = set() # 用於存放生成的唯一id count = 0 # 用於統計出現重複的次數 index = [] # 記錄第幾次呼叫生成8位id出現重複 for i in range(0,20000000): id = get_short_id() if id in id_set: count += 1 index.append(str(i+1)) else: id_set.add(id) print('id:%s,執行第 %s 次,重複數:%s,重複率:%s,出現重複次序 %s' % (id,i+1,count,count/(i+1)*100,','.join(index)))
補充:用python隨機生成以2019開頭的10個8位數的學號
import random意思是引入內建模組random,j代表著
行數,range()是一個隨機生成數字的函式,i控制著
每行的個數,str()表示是轉化為字串的型別
以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。如有錯誤或未考慮完全的地方,望不吝賜教。