Generate random number in range excluding some numbers

笑着哭i 提交于 2020-01-22 20:27:48

问题


Is there a simple way in Python to generate a random number in a range excluding some subset of numbers in that range?

For example, I know that you can generate a random number between 0 and 9 with:

from random import randint
randint(0,9)

What if I have a list, e.g. exclude=[2,5,7], that I don't want to be returned?


回答1:


Try this:

from random import choice

print choice([i for i in range(0,9) if i not in [2,5,7]])



回答2:


Try with something like this:

from random import randint

def my_custom_random():
  exclude=[2,5,7]
  randInt = randint(0,9)
  return my_custom_random() if randInt in exclude else randInt 

print(my_custom_random())


来源:https://stackoverflow.com/questions/42999093/generate-random-number-in-range-excluding-some-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!