Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 当生成随机数作为列表索引时,我应该在哪里减去1?_Python_List_Random - Fatal编程技术网

Python 当生成随机数作为列表索引时,我应该在哪里减去1?

Python 当生成随机数作为列表索引时,我应该在哪里减去1?,python,list,random,Python,List,Random,当我想要列表中的随机项时,我通常会: import random random.randint(0, len(array)-1) (然后将其作为列表的索引) 但是,我想知道做以下事情是否更有效/更好: import random random.randint(1, len(array)) -1 一般来说,使用一种方法比使用另一种方法对执行时间有影响吗?您可以使用如下方法: import random random.randrange(len(array)) # OR random.ran

当我想要列表中的随机项时,我通常会:

import random
random.randint(0, len(array)-1)
(然后将其作为列表的索引)

但是,我想知道做以下事情是否更有效/更好:

import random
random.randint(1, len(array)) -1
一般来说,使用一种方法比使用另一种方法对执行时间有影响吗?您可以使用如下方法:

import random
random.randrange(len(array))  # OR  random.randrange(0, len(array))
或者更好的方法是,使用可读性更强的返回序列外的随机元素:

random.choice(array)

对于此
选项
存在:请尝试

random.choice(your_list)     # returns a random element from the list
运行一些测试(一个循环,使用每种技术生成100000长):

方法1(
random.randint(1,len(lst)-1)

方法2(
random.randint(1,len(lst))-1


因此,它们基本上花费了完全相同的时间-差异几乎可以肯定是随机的-链接到我计算机上的其他活动。

为什么
choice
更好?更优雅吗?
random.randint(0,len(lst))-1)
->
random.randint(1,len(lst))-1)
         14.73
         14.81
         15.04
         14.71
Average: 14.8225
         14.94
         14.91
         14.85
         14.85
Average: 14.8875