前言
有时因为特殊需要不想用sample,但是又得实现相同的功能,于是我就用到另一种实现方法。
且经过实测,发现两种方法的时间复杂度与空间复杂度几乎相同,所以不用担心改为另一种方法后效率降低的问题。
展示
from random import sample, choice
from time import time as t
num = [x for x in range(32 * 1024 ** 2)]
len = 12 * 1024 ** 2
def Sample():
res = sample(num, len)
def Choice():
# 就是改为此方式
res = [choice(num) for x in range(len)]
if __name__ == "__main__":
s = t()
Choice()
e = t() - s
print("Choice函数运行完成,所用时间为{}".format(e))
s = t()
Sample()
e = t() - s
print("Sample函数运行完成,所用时间为{}".format(e))
简而言之就是用choice替换sample