如何从 Python 生成唯一的 64 位整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3530294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate unique 64 bits integers from Python?
提问by Continuation
I need to generate unique 64 bits integers from Python. I've checked out the UUID module. But the UUID it generates are 128 bits integers. So that wouldn't work.
我需要从 Python 生成唯一的 64 位整数。我已经检查了UUID 模块。但是它生成的 UUID 是 128 位整数。所以那行不通。
Do you know of any way to generate 64 bits unique integers within Python? Thanks.
您知道在 Python 中生成 64 位唯一整数的任何方法吗?谢谢。
采纳答案by John La Rooy
just mask the 128bit int
只需屏蔽 128 位 int
>>> import uuid
>>> uuid.uuid4().int & (1<<64)-1
9518405196747027403L
>>> uuid.uuid4().int & (1<<64)-1
12558137269921983654L
These are more or less random, so you have a tiny chance of a collision
这些或多或少是随机的,因此发生碰撞的可能性很小
Perhaps the first 64 bits of uuid1 is safer to use
也许uuid1的前64位使用起来更安全
>>> uuid.uuid1().int>>64
9392468011745350111L
>>> uuid.uuid1().int>>64
9407757923520418271L
>>> uuid.uuid1().int>>64
9418928317413528031L
These are largely based on the clock, so much less random but the uniqueness is better
这些主要基于时钟,随机性要低得多,但唯一性更好
回答by S.Lott
64 bits unique
64 位唯一
What's wrong with counting? A simple counter will create unique values. This is the simplest and it's easy to be sure you won't repeat a value.
计数有什么问题?一个简单的计数器将创建唯一值。这是最简单的,并且很容易确保您不会重复某个值。
Or, if counting isn't good enough, try this.
或者,如果计数不够好,试试这个。
>>> import random
>>> random.getrandbits(64)
5316191164430650570L
Depending on how you seed and use your random number generator, that should be unique.
根据您播种和使用随机数生成器的方式,这应该是唯一的。
You can -- of course -- do this incorrectly and get a repeating sequence of random numbers. Great care must be taken with how you handle seeds for a program that starts and stops.
当然,您可以错误地执行此操作并获得重复的随机数序列。必须非常小心处理启动和停止程序的种子的方式。
回答by Glyph
A 64-bit random number from the OS's random number generator rather than a PRNG:
来自操作系统随机数生成器的 64 位随机数而不是 PRNG:
>>> from struct import unpack; from os import urandom
>>> unpack("!Q", urandom(8))[0]
12494068718269657783L
回答by Chuma Umenze
You can use uuid4()which generates a single random 128-bit integer UUID. We have to 'binary right shift' (>>) each 128-bit integer generated by 64-bit (i.e. 128 - (128 - 64)).
您可以使用uuid4()which 生成一个随机的 128 位整数 UUID。我们必须对>>由 64 位(即128 - (128 - 64))生成的每个 128 位整数“二进制右移”()。
from uuid import uuid4
bit_size = 64
sized_unique_id = uuid4().int >> bit_size
print(sized_unique_id)

