使用random.choice肯定会更快。在
通过查看at the code,可以很容易地解决这个问题。(cpython中的random模块大部分是用Python实现的,只有低级随机数的生成是用C语言实现的。)下面是相关的部分,它们正好挨在一起:def choice(self, seq):
"""Choose a random element from a non-empty sequence."""
try:
i = self._randbelow(len(seq))
except ValueError:
raise IndexError('Cannot choose from an empty sequence') from None
return seq[i]
def shuffle(self, x, random=None):
"""Shuffle list x in place, and return None.
Optional argument random is a 0-argument function returning a
random float in [0.0, 1.0); if it is the default None, the
standard random.random will be used.
"""
if random is None:
randbelow = self._randbelow
for i in reversed(range(1, len(x))):
# pick an element in x[:i+1] with which to exchange x[i]
j = randbelow(i+1)
x[i], x[j] = x[j], x[i]
else:
_int = int
for i in reversed(range(1, len(x))):
# pick an element in x[:i+1] with which to exchange x[i]
j = _int(random() * (i+1))
x[i], x[j] = x[j], x[i]
choice方法只生成一个随机数,并使用它索引到给定的序列中。另一方面,shuffle方法在序列的长度上循环,并在序列中交换元素。因此choice将花费O(1)时间,而{}需要O(N)时间。在
在大多数情况下,如果只需要一个值,则需要使用random.choice。如果需要多个非重复选择,请使用random.sample。只有当您要使用all时,才应该使用random.shuffle。请注意,即使您确实希望选择多个项目,如果您希望同一个项目可以多次被选中,则仍应使用random.choice。采样和洗牌不会重复项目(除非项目在输入列表中重复)。在