如何在范围列表中生成随机数

问题描述 投票:1回答:1

我有一个骰子程序,我有这个:

 import random
 if how_much == "32":
        dice_32 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]
        print(dice_32)

如何使这个更短,到列表生成一个从1到32(或更大)的数字,而不会使列表更大?

python-3.x list random
1个回答
0
投票

您可以使用random.randint()函数在Python中的两个端点之间生成随机整数。这跨越了整个[x,y]间隔,可能包括两个端点:

>>> random.randint(0, 10)
7
>>> random.randint(500, 50000)
18601

使用random.randrange(),您可以排除区间的右侧,这意味着生成的数字始终位于[x,y]内,并且始终小于右侧端点:

>>> random.randrange(1, 10)
5

如果需要生成位于特定[x,y]区间内的随机浮点数,则可以使用random.uniform(),它从连续的均匀分布中获取:

>>> random.uniform(20, 30)
27.42639687016509
>>> random.uniform(30, 40)
36.33865802745107

要从非空序列(如列表或元组)中选择随机元素,可以使用random.choice()。还有random.choices()用于从具有替换的序列中选择多个元素(可以重复):

>>> items = ['one', 'two', 'three', 'four', 'five']
>>> random.choice(items)
'four'

>>> import random
>>> random.randint(1,32)
22

>>> random.randint(1,35)
17

>>> random.randint(1,100)
10

>>> random.randint(1,100)
100

>>> random.randint(1,100)
81

>>> random.randrange(1,100)
91

>>> random.choice(range(100))
60

>>> random.choice(range(100))
55

>>> random.choice(range(100))
58
© www.soinside.com 2019 - 2024. All rights reserved.