我不想说太多细节来保持兴趣,所以这里是要点
我正在从数据库中检索8字符字符串(例如:T12C4F6Z)。我需要不断生成8个字符的字符串,但它们必须是唯一的。我不想针对数据库中的所有内容检查字符串是否存在(或每次查询数据库),而是希望将生成限制为大于数据库最大值的任何内容。这将避免碰撞,而且我不需要每次都检查它是否已经存在
我是这样生成字符串的:
alphabet = "0123456789ASD....."
return ''.join(random.choices(alphabet, k=8))
不必循环检查直到新字符串大于最大值,有人知道如何约束生成吗
编辑:
我正在努力使这个过程更快。 如果max string=zzzz x,我不想开始生成已经存在的字符串,我的想法是将生成限制为zzz y和zzzzz(因为其他所有内容都会发生冲突)
我喜欢直接使用随机发生器。虽然python的random模块相当不错,但对于其他语言,我遇到了一些问题,例如,在多维空间中生成点时,出现了一些模式
Python支持从基数为36的数字转换为十进制整数。因此,要约束最小值,请将字符串转换为整数并使用userrandint,这很容易支持间隔
将常规的基10整数转换为基36更为复杂,幸运的是,您可以使用从https://code.activestate.com/recipes/65212/剪切的附加库,例如或numpy或活动状态。我只是从一个旧的stackoverflow答案中复制了一个被剪掉的,它被讨论了很多次,并且比ActiveState更紧凑
免责声明。python随机数生成器非常好,但它是可能的,因为只有这么多长度为8的唯一字符串。我运行了一些测试,通常需要10万到几百万的时间。即使是一个真正的随机数,你也可以得到任何东西,即使是重复的,只要试着掷硬币或掷骰子几次就行了。请注意,每次更新最大值并不是一个好主意,因为您将用尽列表并很快达到zzzz(可能不到30)。如果您觉得必须100%防止重复,只需构建一个已使用字符串的列表/集合,但这是极不可能的,除非MAX接近zzzz
您可以使用此选项创建唯一的组合:
如果您想从所有可能但唯一的条目中随机抽取连续递增的数字,您可以尝试以下方法:
基本上,您创建所有可能的排列(唯一的组合),然后创建一个随机但唯一的索引列表。现在你对指数进行排序,这就是结果总是在增加的原因。然后通过所有可能排列的对应值匹配索引
关于你最近的答复,我是否可以建议你不要太担心碰撞,采取这样的方法:
这种方法的主要缺点是需要将集合存储在某个地方(pickle并取消pickle),这可能会使数据库中存储的每8个字符的内存使用量增加一倍。如果您的集合对于系统内存来说太大,那么这也将变得不可能。在这种情况下,您可以查看“shelve”模块,该模块提供一个类似dict的数据库对象,您可以通过忽略存储到每个键的值,以与集合基本相同的方式使用该对象
相关问题 更多 >
编程相关推荐