当您使用 range(6) 时,它会返回 0,1,2,3,4,5。您的代码返回一个 60-30-10 列表。
import random
from statistics import mode
numlist = []
for i in range(7):
numlist.append(random.randint(1, 4))
for i in range(2):
numlist.append(random.randint(1, 3))
for i in range(1):
numlist.append(random.randint(1, 2))
这里它包含在一个函数中,可让您确定输出中包含多少个十年。
import random
# stt for seven-twenty-ten
def stt_split(n=1):
# returns lists with lengths that are multiples of ten
numlist = []
for decades in range(n):
for i in range(7):
numlist.append(random.randint(1, 4))
for i in range(2):
numlist.append(random.randint(1, 3))
for i in range(1):
numlist.append(random.randint(1, 2))
return numlist
alice = stt_split()
print(alice) # 10 values in a list
bob = stt_split(4)
print(bob) # 40 values in a list
另一方面,如果您不希望返回具有集合分布的列表,但希望函数返回由随机选择的函数计算的值,则可以尝试类似的方法。
import random
# stt for seven-twenty-ten
def stt_dice(n=1):
# returns lists of random ints with length n
numlist = []
for decades in range(n):
x = random.choices([2, 3, 4], [2, 1, 7])[0]
numlist.append(random.randint(1, x))
return numlist
alice = stt_dice()
print(alice) # 1 value in a list
bob = stt_dice(10)
print(bob) # 10 values in a list