python_random.randint的问题

问题遇到的现象和发生背景

为什么somelist[random.randint(0,len(somelist) - 1)]

我想要达到的结果

想知道为什么这里要加一个-1

因为randInt()函数产生的两个参数区间的随机数,包括两个参数,而列表的下标从0开始,最大下标为列表的长度len-1, 所以产生随机数的也只能在下标0到len-1之间,所以要加个-1.
参考链接:
Python中的randint()方法_cunchi4221的博客-CSDN博客
测试代码:

import random
somelist = [1,2,3,4,5,6] #列表

for i in range(1,10):  #随机从列表somelist取出9个数
    num = somelist[random.randint(0,len(somelist) - 1)];
    #https://m.php.cn/article/471647.html
    print(num,end=" ")



img

因为somelist是列表,下标是从0开始的,最大下表比 len(somelist)小1

我想你的语句应该是这样somelist = [random.randint(0,len(somelist) - 1)]
关于为什么要加-1,因为列表的索引(下标)是从0开始,这个len(somelist)
获取到的是列表的长度,当len(somelist)-1后[random.randint()才能正确遍历列表。

random.randint随机选择列表的索引,len(somelist) 是长度,list下标是从0开始的所以最后一个元素的索引是长度减一即len(somelist) - 1

文章:python生成随机数random.randint()随机取值的概率 中也许有你想要的答案,请看下吧