简体   繁体   English

如何生成在Python中永远唯一的随机数

[英]How to generate random numbers that are unique forever in python

I have written a script where I need a unique random number every time I run that script. 我编写了一个脚本,每次运行该脚本时都需要一个唯一的随机数。 Just for explaination: suppose that I want my script 5 times. 只是为了解释:假设我要我的脚本5次。 Now I want number generated in all times should be unique? 现在我希望所有时间生成的数字应该唯一吗?

I have found a lot of infomation about random number uniqueness but those are for one time only. 我发现了很多有关随机数唯一性的信息,但是这些只是一次。 If you think it is not possible then is there any alternative way etc.? 如果您认为不可能,那么还有其他替代方法吗?

You could use uuid to generate RFC 4122 UUIDs (Universally Unique IDentifiers). 您可以使用uuid生成RFC 4122 UUID(通用唯一IDentifier)。 For example uuid4 generates a random UUID: 例如uuid4生成一个随机的UUID:

In [1]: import uuid

In [2]: u = uuid.uuid4()

In [3]: u
Out[3]: UUID('deb1064a-e885-4ebc-9afc-f5291120edf8')

To get the number, access the int attribute of uuid.UUID objects: 要获取数字,请访问uuid.UUID对象的int属性

In [4]: u.int
Out[4]: 242844464987419882393579831900689854160

Unique and random are contradictory. 唯一和随机是矛盾的。 For anything that's genuinely random there is a (small, maybe infinitessimal) chance of repetition. 对于任何真正随机的东西,都有重复的机会(很小,也许是无穷的)。

If you want something less unwieldy (but less universally unique) than UUIDs you can roll your own combination of a random number (with a small chance of repetition) and a number derived from the time (for example the Unix epoch, which won't ever repeat for a single instance if the script is run less often than once per second). 如果您想要的东西比UUID少一些麻烦(但通用性要小),则可以自己滚动一个随机数(重复的机会很小)和一个从时间派生的数字(例如Unix纪元)的组合如果脚本的运行频率少于每秒一次,则对单个实例重复一次)。

If the random number is used as part of (say) a filename you can generate a name and then check whether the file already exists. 如果将随机数用作(例如)文件名的一部分,则可以生成一个名称,然后检查文件是否已存在。 If it does, then reject the random number as already used, and generate another one. 如果是这样,则拒绝已使用的随机数,并生成另一个。 Or if you really need to, you could store all random numbers already used somewhere. 或者,如果您确实需要,可以将所有已经使用的随机数存储在某个地方。 Load them before each run, add the new number and save after each run. 在每次运行之前加载它们,添加新编号并在每次运行之后保存。

Finally there are pseudo-"random" generators of the form X(n+1) = (X(n)*a + b) mod M. These are hopeless for security / cryptography because given a few members of the sequence, you can discover the algorithm and predict all future numbers. 最后是形式为X(n + 1)=(X(n)* a + b)mod M的伪“随机”生成器。对于安全性/密码学来说,这是无望的,因为给定了序列的几个成员,您可以发现算法并预测所有将来的数字。 However, if that predictability is unimportant, then with appropriate constants you can guarantee no repeats until all M members of the sequence have been generated. 但是,如果可预测性不重要,则可以使用适当的常数来保证在生成序列的所有M个成员之前不会重复。 The numbers are not at all random, but they may appear random to a casual observer. 这些数字不是完全随机的,但是对于偶然的观察者来说,它们可能是随机的。

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

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