[英]How to create a unique alphanumeric id each time and ensure it doesn't exist in my existing list using python?
我需要為用戶分配一個包含單詞“用戶”和某個隨機數的唯一名稱。 像user32944
, user80890
等。 所以我寫了一個這樣的程序
import random
user_list = ["user32944", "user60690"] # essentially this list is what I retrieve from some database
user_name = ""
while(True):
if user_name not in user_list:
user_name = "user" + str(random.random() * 100000).split(".")[0]
break
print(user_name)
但是如果我故意將user_name
設置為列表中已經存在的內容,我的程序不會退出循環並且程序掛起。
我究竟做錯了什么?
您僅在生成的用戶名不在列表中時執行操作,但當用戶名在列表中時您不執行任何操作。 因此,您不會退出 while 循環,程序將掛起。
以下代碼示例執行您想要的操作。 盡管我建議您在 python 中探索uuid 包。
import random
user_list = ["user32944", "user60690"] # essentially this list is what I retrieve from some database
def generateRandomUsername():
randomNr = random.randint(1,3)
if randomNr == 1:
return "user32944"
else:
return "user" + str(random.random() * 100000).split(".")[0]
def getRandomUniqueUsername():
while(True):
username = generateRandomUsername()
if username not in user_list:
print('Created user \'%s\'' % username)
return username
else:
print("Username \'%s\'already exists, generating new one" % username)
def printUsernameList():
for username in user_list:
print('Username: %s' % username)
#Create 4 random usernames
for i in range(4):
username = getRandomUniqueUsername()
user_list.append(username)
print('Printing user_list...')
printUsernameList()
這永遠不會退出循環,因為您永遠不會滿足 IF 條件,並且 while 上也沒有條件表達式,您在 while 條件中給出了 True -> 這意味着它無限循環。
因此,如果您不滿足 IF 條件,請編寫一個邏輯,以防萬一 IF 沒有得到 statisified 然后跳出循環。
如果你只想要帶有隨機字母數字 ID 的 guid,那么在 python 中使用 uuid 包。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.