简体   繁体   English

python systemrandom用于唯一数字

[英]python systemrandom for unique numbers

I need to generate a globally unique integer identifier. 我需要生成一个全局唯一的整数标识符。

Does the number generated using 请问使用

from random import SystemRandom
SystemRandom().getrandbits(64)

Is guaranteed to be unique? 保证是唯一的?

No. In general, random number generators can't ensure uniqueness of the numbers they produce. 不能。通常,随机数生成器无法确保其生成的数字的唯一性。 (There are specific algorithms that can generate a sequence of unique random-looking numbers, including "full-period" linear congruential generators, but it's not generally the case that an RNG produces unique random numbers.) (有一些特定的算法可以生成一系列唯一的随机数,包括“全周期”线性同余生成器,但是RNG 通常不会生成唯一的随机数。)

However, there are several things to keep in mind when generating unique identifiers (and I mention them in " Unique Random Identifiers "). 但是,生成唯一标识符时要牢记一些事情(我在“ 唯一随机标识符 ”中提到了它们)。 You should give further information in your question on why you need unique identifiers, so that I can help you better. 您应该在问题中提供更多信息,说明为什么需要唯一标识符,以便我更好地帮助您。

It is not guaranteed, but if you test you can that is almost impossible to generate the same number twice. 不能保证,但是如果您进行测试,几乎不可能两次生成相同的数字。 I was working in something like that some time ago, and found this: How can I create a random number that is cryptographically secure in python? 一段时间之前,我正在从事类似的工作,并且发现了这一点: 我如何创建在python中具有加密安全性的随机数?

I don't know the context of your question, but if you wnat to get a unique code or something like that, you try using GUID. 我不知道您的问题的上下文,但是如果您想获得唯一的代码或类似的代码,请尝试使用GUID。 Link: https://www.geeksforgeeks.org/generating-random-ids-using-uuid-python/ 链接: https//www.geeksforgeeks.org/generating-random-ids-using-uuid-python/

Not only that random numbers are not guaranteed to be unique. 不仅不能保证随机数是唯一的。 They must not be guaranteed to be unique, or they would not be truly random. 不能保证它们是唯一的,否则它们不是真正随机的。 Therefore, it is perfectly valid (although very very unlikely, one can easily calculate exactly how unlikey) to get the same number 100 times in a row from a perfect random generator. 因此,从一个完美的随机生成器中连续获取100个相同的数字是完全有效的(尽管非常不可能,但是可以很容易地精确计算出它的不可能性)。

If you want unique identifiers, use UUIDs. 如果需要唯一标识符,请使用UUID。 They are meant for that purpose. 它们就是为了这个目的。 Are they guaranteed to be unique? 是否保证它们是唯一的? Not exactly, but let's say they are unique enough that you should not care about the details. 不完全是,但可以说它们足够独特,您无需关心细节。 They are the standard way to do that. 它们是执行此操作的标准方法。 Use them. 使用它们。

>>> import uuid
>>> uuid.uuid4()
UUID('bc64667f-503c-416e-964d-93486a02f3fd')

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

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