English 中文(简体)
如何产生随机数字,具体数字多少?
原标题:How to generate a random number with a specific amount of digits?

让我说,我需要3位数,这样,就象:

>>> random(3)
563

or

>>> random(5)
26748
>> random(2)
56
最佳回答
问题回答

如果你想把它当作一个扼杀(例如10位数的电话号码)的话,你可以这样做:

n = 10
  .join(["{}".format(randint(0, 9)) for num in range(0, n)])

如果需要3位数,并希望001-099有效号码,那么你仍应使用比替代物更快的宽度/宽度。 仅加上从胎体转为胎体之前的死胎。

import random
num = random.randrange(1, 10**3)
# using format
num_with_zeros =  {:03} .format(num)
# using string s zfill
num_with_zeros = str(num).zfill(3)

或者,如果你不希望节省随机数目,那么你就能够这样做。

 {:03} .format(random.randrange(1, 10**3))

pthon 3.6 + only oneliner:

f {random.randrange(1, 10**3):03} 

上文列举的产出如下:

  • 026
  • 255
  • 512

作为一项职能执行,不仅可以支持3位数的长度:

import random

def n_len_rand(len_, floor=1):
    top = 10**len_
    if floor > top:
        raise ValueError(f"Floor  {floor}  must be less than requested top  {top} ")
    return f {random.randrange(floor, top):0{len_}} 

你可以写一下,做你想要做的事情,没有什么作用:

import random
def randomDigits(digits):
    lower = 10**(digits-1)
    upper = 10**digits - 1
    return random.randint(lower, upper)

基本上,10** (数-1)给予你最小的{数}-位数,10** 位数- 1使你获得最大数目的{数}-位数(即最小的{数+1}-位数减去数)。 页: 1 然后,我们只是从这个范围随机抽调。

是否算是可能的第一位数? 如果是的话,你需要<条码>。 如果没有,random.randint(10**(n-1),10**n-1)。 如果允许零never<>>,那么你就不得不明确拒绝其中的零号,或取下n<>n<>t>>>。

另外:令人感兴趣的是,<代码>randint(a,b)使用一些非慢性“索引”,以获得随机编号<代码>a <=n <=b。 人们可能期望它像<代码>range那样工作,并生成随机编号a <=n <b。 (注:闭门顶端。)

鉴于关于<代码>randrange的评论中的答复,注意到这些答复可替换为“更清洁的代码>random.randrange(0,10**n)、ran.randrange(10**(n-1),10**n)ran.rand (1,10)

import random

fixed_digits = 6 

print(random.randrange(111111, 999999, fixed_digits))

out:
271533

你们可以创造一种功能,消费一个暗中的清单,改变扼杀,再造,如:

import random

def generate_random_number(length):
    return int(  .join([str(random.randint(0,10)) for _ in range(length)]))

页: 1 缩略语:

import random
first = random.randint(1,9)
first = str(first)
n = 5

nrs = [str(random.randrange(10)) for i in range(n-1)]
for i in range(len(nrs))    :
    first += str(nrs[i])

print str(first)

我知道这是一个老问题,但我多年来看到许多解决办法。 我在此建议设立一个职能,在出现违约的情况下设立一位数位数的随机座标。 6. 结 论

from random import randint

def OTP(n=6):
    n = 1 if n< 1 else n
    return randint(int("1"*n), int("9"*n))

当然,你可以把“1”改为你想要开端的东西。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签