如何生成随机数,同时避免已使用的数字
我如何生成随机数,但让这些数字避免已使用的数字。 我有一个包含数千组数字的 TXT 文件,我需要生成一系列随机数,同时避免这些数字。
IE、TXT - 0102030405
我的随机数需要避免这个数字。
顺便说一句,我如何将 TXT 10 位数字拆分为 5 个两位数数字? 那么我如何根据它生成随机数。
How do i generate random numbers but have the numbers avoid numbers already used.
I have a TXT file with thousands of sets of numbers and i need to generate a series of random numbers while avoiding these.
IE, TXT - 0102030405
my random number needs to avoid this number.
on a side note, how can i split up the TXT 10 digit number into 5, two digit numbers?
then how can i generate random numbers based off of that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将所有以前找到的随机数加载到字典中,然后只需检查字典中是否有 new_random ,如果是,则尝试新的随机数。
对于第二方,假设您的十位数号码存储在变量 ten_digits 中。
你可以通过以下方式将其分解为 5 个两位数
You could load up all previously found random numbers into a dictionary, then just check whether new_random in dictionary, and if it is try a new random number.
For the second party, say your ten digit number is stored in variable ten_digits.
you can break this up into 5 two digit numbers by doing
如果您需要维护该文件(我认为您这样做是为了添加新数字),我建议您“忘记”使用纯文本文件并使用 SQLite 或任何其他在文件中备份的嵌入式数据库,因为您可能不想将所有数字加载到内存中。
您想要从 SQLite 获得的“功能”(或更准确地说,数据结构)是 B 树,因此您可以快速检索数字。我这么说是因为你也可以尝试找到一个实现 B-Tree 的库,然后你就不需要 SQLite 了。
If you need to maintain the file (which I think you do, in order to add new numbers), I would suggest you to "forget" using a plain text file and use SQLite or any other embedded DB that is backed up in a file, as you probably don't want to load all the numbers in memory.
The "feature" (or better said, data structure) you want from SQLite is a B-Tree, so you can retrieve the numbers fast. I'm saying this, because you could also try to find a library that implements B-Trees, and then you wouldn't need SQLite.
您使用这些数字作为 ID 吗?您可能应该考虑使用哈希表。
http://en.wikipedia.org/wiki/Hash_table
我对Python不太熟悉但我确信有一个子字符串函数,您可以给它(作为参数)一个索引来启动子字符串和要复制的字符数。
Are you using the numbers as IDs? You should probably look into using a hash table.
http://en.wikipedia.org/wiki/Hash_table
I'm not terribly familiar with Python but I'm sure there is a substring function you can give it (as arguments) an index to start the substring and the number of characters to copy.
如果您的列表相对较小,您可以将其加载到 set< /a> 并检查:
要分割数字,您可以使用切片:
If you your list is relatively small you could load it into a set and check against that:
To split the number you could use slices: