random.choice()在同一秒返回相同的值,如何避免它呢? [英] random.choice() returns same value at the same second, how does one avoid it?

查看:701
本文介绍了random.choice()在同一秒返回相同的值,如何避免它呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找有关如何在python中生成随机数的类似问题.例如:类似问题-但是我没有出现randomfunction返回的问题每次都有相同的值.

I have been looking at similar questions regarding how to generate random numbers in python. Example: Similar Question - but i do not have the problem that the randomfunction returns same values every time.

我的随机数发生器工作正常,问题是在我认为不希望的同一秒调用函数时,它返回相同的值.

My random generator works fine, the problem is that it returns the same value when calling the function at, what I think, the same second which is undesireable.

我的代码如下

def getRandomID():
    token = ''
    letters = "abcdefghiklmnopqrstuvwwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
    for i in range(1,36):
        token = token + random.choice(letters)
    return token

正如我提到的,此函数在不同时间调用时返回不同的值,但在同时调用该函数时返回相同的值.我如何避免这个问题?

As I mentioned this function returns different values when being called at on different times but returns the same value when calling the function at the same time. How do I avoid this problem?

我在后端服务器中使用此功能来生成唯一的ID,以供前端用户插入数据库中,因此发生这种情况时,我无法控制时间间隔.我必须具有随机令牌才能映射数据库中的用户,以便能够使用数据库中的队列号正确插入用户.

I use this function in a back-end-server to generate unique IDs for users in front-end to insert in a database so I cannot control the time intervals when this happens. I must have random tokens to map the users in the database to be able to insert them correctly with queuenumbers in the database.

推荐答案

您可以使用random.SystemRandom()来改善问题,如下所示:

You could possibly improve matters by using random.SystemRandom() as follows:

import random

sys_random = random.SystemRandom()

def getRandomID():
    token = ''
    letters = "abcdefghiklmnopqrstuvwwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
    for i in range(1, 36):
        token = token + sys_random.choice(letters)
    return token

print(getRandomID())

这尝试使用os.urandom()函数,该函数从操作系统提供的源生成随机数. .choices() 函数可以也可用于在单个调用中返回选择列表,避免字符串串联:

This attempts to use the os.urandom() function which generates random numbers from sources provided by the operating system. The .choices() function could also be used to return a list of choices in a single call, avoiding the string concatenation:

import random

sys_random = random.SystemRandom()

def getRandomID():
    letters = "abcdefghiklmnopqrstuvwwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
    return ''.join(sys_random.choices(letters, k=35))

print(getRandomID())

这篇关于random.choice()在同一秒返回相同的值,如何避免它呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆