python - Select n random number from a sorted list of numbers -
i have list of numbers in sorted order. there may gaps between consecutive numbers
. wrote following code find 50k random numbers list, takes time. there efficient version this?
def selectnrandomvalsfromalist(mylist, n): retval = [] randomchoice = random.choice mylistremove = mylist.remove retvalappend = retval.append in range(n): value = randomchoice(mylist) mylistremove(value) retvalappend(value) return(retval) mylist = range(2000000) n =50000 selectnrandomvalsfromalist(mylist,n)
don't reinvent wheel. use random.sample:
return k length list of unique elements chosen population sequence. used random sampling without replacement.
>>> import random >>> l = range(20) >>> random.sample(l, 10) [6, 15, 13, 3, 2, 4, 14, 17, 7, 10]
Comments
Post a Comment