标签归档:integer

生成0到9之间的随机整数

问题:生成0到9之间的随机整数

如何在Python中生成0到9(含)之间的随机整数?

例如,0123456789

How can I generate random integers between 0 and 9 (inclusive) in Python?

For example, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9


回答 0

尝试:

from random import randrange
print(randrange(10))

更多信息:http : //docs.python.org/library/random.html#random.randrange

Try:

from random import randrange
print(randrange(10))

More info: http://docs.python.org/library/random.html#random.randrange


回答 1

import random
print(random.randint(0,9))

random.randint(a, b)

返回一个随机整数N,使得a <= N <= b。

文件:https//docs.python.org/3.1/library/random.html#random.randint

import random
print(random.randint(0,9))

random.randint(a, b)

Return a random integer N such that a <= N <= b.

Docs: https://docs.python.org/3.1/library/random.html#random.randint


回答 2

尝试这个:

from random import randrange, uniform

# randrange gives you an integral value
irand = randrange(0, 10)

# uniform gives you a floating-point value
frand = uniform(0, 10)

Try this:

from random import randrange, uniform

# randrange gives you an integral value
irand = randrange(0, 10)

# uniform gives you a floating-point value
frand = uniform(0, 10)

回答 3

from random import randint

x = [randint(0, 9) for p in range(0, 10)]

这将生成10个伪随机整数,范围在0到9之间(含0和9)。

from random import randint

x = [randint(0, 9) for p in range(0, 10)]

This generates 10 pseudorandom integers in range 0 to 9 inclusive.


回答 4

secrets模块是Python 3.6中的新增功能。这比random用于加密或安全用途的模块更好。

要随机打印范围为0-9的整数:

from secrets import randbelow
print(randbelow(10))

有关详细信息,请参阅PEP 506

The secrets module is new in Python 3.6. This is better than the random module for cryptography or security uses.

To randomly print an integer in the inclusive range 0-9:

from secrets import randbelow
print(randbelow(10))

For details, see PEP 506.


回答 5

选择数组的大小(在此示例中,我选择的大小为20)。然后,使用以下命令:

import numpy as np   
np.random.randint(10, size=(1, 20))

您可以期望看到以下形式的输出(每次运行它都会返回不同的随机整数;因此,您可以期望输出数组中的整数与下面给出的示例有所不同)。

array([[1, 6, 1, 2, 8, 6, 3, 3, 2, 5, 6, 5, 0, 9, 5, 6, 4, 5, 9, 3]])

Choose the size of the array (in this example, I have chosen the size to be 20). And then, use the following:

import numpy as np   
np.random.randint(10, size=(1, 20))

You can expect to see an output of the following form (different random integers will be returned each time you run it; hence you can expect the integers in the output array to differ from the example given below).

array([[1, 6, 1, 2, 8, 6, 3, 3, 2, 5, 6, 5, 0, 9, 5, 6, 4, 5, 9, 3]])

回答 6

尝试通过 random.shuffle

>>> import random
>>> nums = range(10)
>>> random.shuffle(nums)
>>> nums
[6, 3, 5, 4, 0, 1, 2, 9, 8, 7]

Try this through random.shuffle

>>> import random
>>> nums = range(10)
>>> random.shuffle(nums)
>>> nums
[6, 3, 5, 4, 0, 1, 2, 9, 8, 7]

回答 7

我会尝试以下之一:

1.> numpy.random.randint

import numpy as np
X1 = np.random.randint(low=0, high=10, size=(15,))

print (X1)
>>> array([3, 0, 9, 0, 5, 7, 6, 9, 6, 7, 9, 6, 6, 9, 8])

2.> numpy.random.uniform

import numpy as np
X2 = np.random.uniform(low=0, high=10, size=(15,)).astype(int)

print (X2)
>>> array([8, 3, 6, 9, 1, 0, 3, 6, 3, 3, 1, 2, 4, 0, 4])

3.> random.randrange

from random import randrange
X3 = [randrange(10) for i in range(15)]

print (X3)
>>> [2, 1, 4, 1, 2, 8, 8, 6, 4, 1, 0, 5, 8, 3, 5]

4.> random.randint

from random import randint
X4 = [randint(0, 9) for i in range(0, 15)]

print (X4)
>>> [6, 2, 6, 9, 5, 3, 2, 3, 3, 4, 4, 7, 4, 9, 6]

速度:

np.random.randint最快的,其次是np.random.uniformrandom.randrangerandom.randint最慢的

►两者np.random.randintnp.random.uniform快得多(〜8 – 12倍的速度)比random.randrange和random.randint

%timeit np.random.randint(low=0, high=10, size=(15,))
>> 1.64 µs ± 7.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit np.random.uniform(low=0, high=10, size=(15,)).astype(int)
>> 2.15 µs ± 38.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit [randrange(10) for i in range(15)]
>> 12.9 µs ± 60.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit [randint(0, 9) for i in range(0, 15)]
>> 20 µs ± 386 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

笔记:

1.> np.random.randint在半开间隔[low,high)内生成随机整数。

2.> np.random.uniform在半开间隔[low,high)内生成均匀分布的数字。

3.> random.randrange(停止)从range(开始,停止,步进)生成一个随机数。

4.> random.randint(a,b)返回一个随机整数N,使得a <= N <= b。

5.> astype(int)将numpy数组转换为int数据类型。

6.>我选择尺寸=(15,)。这将为您提供一个长度为15的numpy数组。

I would try one of the following:

1.> numpy.random.randint

import numpy as np
X1 = np.random.randint(low=0, high=10, size=(15,))

print (X1)
>>> array([3, 0, 9, 0, 5, 7, 6, 9, 6, 7, 9, 6, 6, 9, 8])

2.> numpy.random.uniform

import numpy as np
X2 = np.random.uniform(low=0, high=10, size=(15,)).astype(int)

print (X2)
>>> array([8, 3, 6, 9, 1, 0, 3, 6, 3, 3, 1, 2, 4, 0, 4])

3.> random.randrange

from random import randrange
X3 = [randrange(10) for i in range(15)]

print (X3)
>>> [2, 1, 4, 1, 2, 8, 8, 6, 4, 1, 0, 5, 8, 3, 5]

4.> random.randint

from random import randint
X4 = [randint(0, 9) for i in range(0, 15)]

print (X4)
>>> [6, 2, 6, 9, 5, 3, 2, 3, 3, 4, 4, 7, 4, 9, 6]

Speed:

np.random.randint is the fastest, followed by np.random.uniform and random.randrange. random.randint is the slowest.

► Both np.random.randint and np.random.uniform are much faster (~8 – 12 times faster) than random.randrange and random.randint .

%timeit np.random.randint(low=0, high=10, size=(15,))
>> 1.64 µs ± 7.83 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit np.random.uniform(low=0, high=10, size=(15,)).astype(int)
>> 2.15 µs ± 38.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit [randrange(10) for i in range(15)]
>> 12.9 µs ± 60.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit [randint(0, 9) for i in range(0, 15)]
>> 20 µs ± 386 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Notes:

1.> np.random.randint generates random integers over the half-open interval [low, high).

2.> np.random.uniform generates uniformly distributed numbers over the half-open interval [low, high).

3.> random.randrange(stop) generates a random number from range(start, stop, step).

4.> random.randint(a, b) returns a random integer N such that a <= N <= b.

5.> astype(int) casts the numpy array to int data type.

6.> I have chosen size = (15,). This will give you a numpy array of length = 15.


回答 8

如果是连续数字randintrandrange可能是最佳选择,但是如果序列中有多个不同的值(即a list),则也可以使用choice

>>> import random
>>> values = list(range(10))
>>> random.choice(values)
5

choice 也适用于非连续样本中的一项:

>>> values = [1, 2, 3, 5, 7, 10]
>>> random.choice(values)
7

如果您需要“密码学上很强大”,则secrets.choice在python 3.6及更高版本中也有:

>>> import secrets
>>> values = list(range(10))
>>> secrets.choice(values)
2

In case of continuous numbers randint or randrange are probably the best choices but if you have several distinct values in a sequence (i.e. a list) you could also use choice:

>>> import random
>>> values = list(range(10))
>>> random.choice(values)
5

choice also works for one item from a not-continuous sample:

>>> values = [1, 2, 3, 5, 7, 10]
>>> random.choice(values)
7

If you need it “cryptographically strong” there’s also a secrets.choice in python 3.6 and newer:

>>> import secrets
>>> values = list(range(10))
>>> secrets.choice(values)
2

回答 9

虽然许多文章都演示了如何获取一个随机整数,但最初的问题是询问如何生成随机整数s(复数):

如何在Python中生成0到9(含)之间的随机整数?

为了清楚起见,这里我们演示如何获取多个随机整数。

给定

>>> import random


lo = 0
hi = 10
size = 5

多个随机整数

# A
>>> [lo + int(random.random() * (hi - lo)) for _ in range(size)]
[5, 6, 1, 3, 0]

# B
>>> [random.randint(lo, hi) for _ in range(size)]
[9, 7, 0, 7, 3]

# C
>>> [random.randrange(lo, hi) for _ in range(size)]
[8, 3, 6, 8, 7]

# D
>>> lst = list(range(lo, hi))
>>> random.shuffle(lst)
>>> [lst[i] for i in range(size)]
[6, 8, 2, 5, 1]

# E
>>> [random.choice(range(lo, hi)) for _ in range(size)]
[2, 1, 6, 9, 5]

随机整数样本

# F
>>> random.choices(range(lo, hi), k=size)
[3, 2, 0, 8, 2]

# G
>>> random.sample(range(lo, hi), k=size)
[4, 5, 1, 2, 3]

细节

一些文章演示了如何本地生成多个随机整数。1 以下是一些解决隐含问题的选项:

另请参阅R.Hettinger 关于“块和别名” 的演讲,并使用以下示例random模块中的。

这是标准库和Numpy中一些随机函数的比较:

| | random                | numpy.random                     |
|-|-----------------------|----------------------------------|
|A| random()              | random()                         |
|B| randint(low, high)    | randint(low, high)               |
|C| randrange(low, high)  | randint(low, high)               |
|D| shuffle(seq)          | shuffle(seq)                     |
|E| choice(seq)           | choice(seq)                      |
|F| choices(seq, k)       | choice(seq, size)                |
|G| sample(seq, k)        | choice(seq, size, replace=False) |

您还可以将Numpy中的许多分布之一快速转换为随机整数样本。3

例子

>>> np.random.normal(loc=5, scale=10, size=size).astype(int)
array([17, 10,  3,  1, 16])

>>> np.random.poisson(lam=1, size=size).astype(int)
array([1, 3, 0, 2, 0])

>>> np.random.lognormal(mean=0.0, sigma=1.0, size=size).astype(int)
array([1, 3, 1, 5, 1])

1即@John Lawrence Aspden,@ ST Mohammed,@ SiddTheKid,@ user14372,@ zangw等。 2 @prashanth提到此模块显示一个整数。 3由@Siddharth Satpathy演示

While many posts demonstrate how to get one random integer, the original question asks how to generate random integers (plural):

How can I generate random integers between 0 and 9 (inclusive) in Python?

For clarity, here we demonstrate how to get multiple random integers.

Given

>>> import random


lo = 0
hi = 10
size = 5

Code

Multiple, Random Integers

# A
>>> [lo + int(random.random() * (hi - lo)) for _ in range(size)]
[5, 6, 1, 3, 0]

# B
>>> [random.randint(lo, hi) for _ in range(size)]
[9, 7, 0, 7, 3]

# C
>>> [random.randrange(lo, hi) for _ in range(size)]
[8, 3, 6, 8, 7]

# D
>>> lst = list(range(lo, hi))
>>> random.shuffle(lst)
>>> [lst[i] for i in range(size)]
[6, 8, 2, 5, 1]

# E
>>> [random.choice(range(lo, hi)) for _ in range(size)]
[2, 1, 6, 9, 5]

Sample of Random Integers

# F
>>> random.choices(range(lo, hi), k=size)
[3, 2, 0, 8, 2]

# G
>>> random.sample(range(lo, hi), k=size)
[4, 5, 1, 2, 3]

Details

Some posts demonstrate how to natively generate multiple random integers.1 Here are some options that address the implied question:

See also R. Hettinger’s talk on Chunking and Aliasing using examples from the random module.

Here is a comparison of some random functions in the Standard Library and Numpy:

| | random                | numpy.random                     |
|-|-----------------------|----------------------------------|
|A| random()              | random()                         |
|B| randint(low, high)    | randint(low, high)               |
|C| randrange(low, high)  | randint(low, high)               |
|D| shuffle(seq)          | shuffle(seq)                     |
|E| choice(seq)           | choice(seq)                      |
|F| choices(seq, k)       | choice(seq, size)                |
|G| sample(seq, k)        | choice(seq, size, replace=False) |

You can also quickly convert one of many distributions in Numpy to a sample of random integers.3

Examples

>>> np.random.normal(loc=5, scale=10, size=size).astype(int)
array([17, 10,  3,  1, 16])

>>> np.random.poisson(lam=1, size=size).astype(int)
array([1, 3, 0, 2, 0])

>>> np.random.lognormal(mean=0.0, sigma=1.0, size=size).astype(int)
array([1, 3, 1, 5, 1])

1Namely @John Lawrence Aspden, @S T Mohammed, @SiddTheKid, @user14372, @zangw, et al. 2@prashanth mentions this module showing one integer. 3Demonstrated by @Siddharth Satpathy


回答 10

如果要使用numpy,请使用以下命令:

import numpy as np
print(np.random.randint(0,10))

if you want to use numpy then use the following:

import numpy as np
print(np.random.randint(0,10))

回答 11

>>> import random
>>> random.randrange(10)
3
>>> random.randrange(10)
1

要获取十个样本的列表:

>>> [random.randrange(10) for x in range(10)]
[9, 0, 4, 0, 5, 7, 4, 3, 6, 8]
>>> import random
>>> random.randrange(10)
3
>>> random.randrange(10)
1

To get a list of ten samples:

>>> [random.randrange(10) for x in range(10)]
[9, 0, 4, 0, 5, 7, 4, 3, 6, 8]

回答 12

生成0到9之间的随机整数。

import numpy
X = numpy.random.randint(0, 10, size=10)
print(X)

输出:

[4 8 0 4 9 6 9 9 0 7]

Generating random integers between 0 and 9.

import numpy
X = numpy.random.randint(0, 10, size=10)
print(X)

Output:

[4 8 0 4 9 6 9 9 0 7]

回答 13

random.sample 是另一个可以使用的

import random
n = 1 # specify the no. of numbers
num = random.sample(range(10),  n)
num[0] # is the required number

random.sample is another that can be used

import random
n = 1 # specify the no. of numbers
num = random.sample(range(10),  n)
num[0] # is the required number

回答 14

最好的方法是使用导入随机函数

import random
print(random.sample(range(10), 10))

或没有任何库导入:

n={} 
for i in range(10):
    n[i]=i

for p in range(10):
    print(n.popitem()[1])

这里的popitems从字典中删除并返回一个任意值n

Best way is to use import Random function

import random
print(random.sample(range(10), 10))

or without any library import:

n={} 
for i in range(10):
    n[i]=i

for p in range(10):
    print(n.popitem()[1])

here the popitems removes and returns an arbitrary value from the dictionary n.


回答 15

这更多是一种数学方法,但100%的时间有效:

假设您要使用random.random()函数生成介于a和之间的数字b。为此,只需执行以下操作:

num = (b-a)*random.random() + a;

当然,您可以生成更多数字。

This is more of a mathematical approach but it works 100% of the time:

Let’s say you want to use random.random() function to generate a number between a and b. To achieve this, just do the following:

num = (b-a)*random.random() + a;

Of course, you can generate more numbers.


回答 16

随机模块的文档页面:

警告:出于安全目的,不应使用此模块的伪随机数生成器。如果需要加密安全的伪随机数生成器,请使用os.urandom()或SystemRandom。

Python 2.4中引入的random.SystemRandom被认为是加密安全的。在编写本文时,它在Python 3.7.1中仍然可用。

>>> import string
>>> string.digits
'0123456789'
>>> import random
>>> random.SystemRandom().choice(string.digits)
'8'
>>> random.SystemRandom().choice(string.digits)
'1'
>>> random.SystemRandom().choice(string.digits)
'8'
>>> random.SystemRandom().choice(string.digits)
'5'

代替string.digitsrange可以与理解一起用于其他一些答案。根据您的需要混合搭配。

From the documentation page for the random module:

Warning: The pseudo-random generators of this module should not be used for security purposes. Use os.urandom() or SystemRandom if you require a cryptographically secure pseudo-random number generator.

random.SystemRandom, which was introduced in Python 2.4, is considered cryptographically secure. It is still available in Python 3.7.1 which is current at time of writing.

>>> import string
>>> string.digits
'0123456789'
>>> import random
>>> random.SystemRandom().choice(string.digits)
'8'
>>> random.SystemRandom().choice(string.digits)
'1'
>>> random.SystemRandom().choice(string.digits)
'8'
>>> random.SystemRandom().choice(string.digits)
'5'

Instead of string.digits, range could be used per some of the other answers along perhaps with a comprehension. Mix and match according to your needs.


回答 17

OpenTURNS不仅可以模拟随机整数,还可以使用 UserDefined定义的类。

以下模拟了分布的12个结果。

import openturns as ot
points = [[i] for i in range(10)]
distribution = ot.UserDefined(points) # By default, with equal weights.
for i in range(12):
    x = distribution.getRealization()
    print(i,x)

打印:

0 [8]
1 [7]
2 [4]
3 [7]
4 [3]
5 [3]
6 [2]
7 [9]
8 [0]
9 [5]
10 [9]
11 [6]

括号之所以存在,x是因为它是一Point维的。只需调用以下命令即可产生12个结果getSample

sample = distribution.getSample(12)

会生成:

>>> print(sample)
     [ v0 ]
 0 : [ 3  ]
 1 : [ 9  ]
 2 : [ 6  ]
 3 : [ 3  ]
 4 : [ 2  ]
 5 : [ 6  ]
 6 : [ 9  ]
 7 : [ 5  ]
 8 : [ 9  ]
 9 : [ 5  ]
10 : [ 3  ]
11 : [ 2  ]

有关此主题的更多详细信息,请参见:http : //openturns.github.io/openturns/master/user_manual/_genic/openturns.UserDefined.html

OpenTURNS allows to not only simulate the random integers but also to define the associated distribution with the UserDefined defined class.

The following simulates 12 outcomes of the distribution.

import openturns as ot
points = [[i] for i in range(10)]
distribution = ot.UserDefined(points) # By default, with equal weights.
for i in range(12):
    x = distribution.getRealization()
    print(i,x)

This prints:

0 [8]
1 [7]
2 [4]
3 [7]
4 [3]
5 [3]
6 [2]
7 [9]
8 [0]
9 [5]
10 [9]
11 [6]

The brackets are there becausex is a Point in 1-dimension. It would be easier to generate the 12 outcomes in a single call to getSample:

sample = distribution.getSample(12)

would produce:

>>> print(sample)
     [ v0 ]
 0 : [ 3  ]
 1 : [ 9  ]
 2 : [ 6  ]
 3 : [ 3  ]
 4 : [ 2  ]
 5 : [ 6  ]
 6 : [ 9  ]
 7 : [ 5  ]
 8 : [ 9  ]
 9 : [ 5  ]
10 : [ 3  ]
11 : [ 2  ]

More details on this topic are here: http://openturns.github.io/openturns/master/user_manual/_generated/openturns.UserDefined.html


回答 18

我对Python 3.6有了更好的运气

str_Key = ""                                                                                                
str_RandomKey = ""                                                                                          
for int_I in range(128):                                                                                    
      str_Key = random.choice('0123456789')
      str_RandomKey = str_RandomKey + str_Key 

只需添加“ ABCD”和“ abcd”或“ ^!〜=-> <”之类的字符即可更改要提取的字符池,更改范围以更改生成的字符数。

I had better luck with this for Python 3.6

str_Key = ""                                                                                                
str_RandomKey = ""                                                                                          
for int_I in range(128):                                                                                    
      str_Key = random.choice('0123456789')
      str_RandomKey = str_RandomKey + str_Key 

Just add characters like ‘ABCD’ and ‘abcd’ or ‘^!~=-><‘ to alter the character pool to pull from, change the range to alter the number of characters generated.