简体   繁体   English

如何每次创建一个唯一的字母数字 id 并确保它不存在于我使用 python 的现有列表中?

[英]How to create a unique alphanumeric id each time and ensure it doesn't exist in my existing list using python?

I need to assign a unique name that contains the word 'user' and a certain random numbers to a user.我需要为用户分配一个包含单词“用户”和某个随机数的唯一名称。 Something like user32944 , user80890 etc. So I write a program something like thisuser32944user80890等。 所以我写了一个这样的程序

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)

But if I deliberately set the user_name to something that already exists in the list, my program doesn't exit the loop and the program hangs.但是如果我故意将user_name设置为列表中已经存在的内容,我的程序不会退出循环并且程序挂起。

What am I doing wrong?我究竟做错了什么?

You only perform a action when the generated username is not in the list, but you don't do anything when the username is in the list.您仅在生成的用户名不在列表中时执行操作,但当用户名在列表中时您不执行任何操作。 And therefore you don't exit the while loop and the program will hang.因此,您不会退出 while 循环,程序将挂起。

The following code sample does what you want.以下代码示例执行您想要的操作。 Although i recommend you to explore the uuid package in python.尽管我建议您在 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()

That will never exit the loop because you are never satisfying the IF condition and there is no conditional expression on while too, you gave True in while condition -> which means it loops infinitely.这永远不会退出循环,因为您永远不会满足 IF 条件,并且 while 上也没有条件表达式,您在 while 条件中给出了 True -> 这意味着它无限循环。

So if you do not satsifying the IF condition then write a logic what you would want to do incase IF does not get statisified and then break out of the loop.因此,如果您不满足 IF 条件,请编写一个逻辑,以防万一 IF 没有得到 statisified 然后跳出循环。

And if you want guid with just random alphanumeric ids, then use uuid package in python.如果你只想要带有随机字母数字 ID 的 guid,那么在 python 中使用 uuid 包。

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

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