简体   繁体   English

生成从python范围中排除一个数字的随机数

[英]generate random number that excludes one number from the range python

I am generating a number from the range of 1 to 10 but would like to exclude the number 2 from that range i have no idea how to go about doing this. 我正在生成1到10范围内的数字,但想从该范围中排除数字2我不知道该怎么做。

This is what i have so far. 这是我到目前为止所拥有的。

python file python文件

move =  random.randint(1, 10)

So to round of: I want to generate numbers between 1 to 10 and exclude number 2 . 所以回合:我想生成1 to 10之间的数字,并排除数字2

您可以使用random.choice

move =  random.choice([1, 3, 4, 5, 6, 7, 8, 9, 10])

You can generate a random value from 1 to 9 instead and shift it by one if it is bigger or equal to 2. 您可以生成一个从1到9的随机值,如果大于或等于2,则将其移位1。

value =  random.randint(1, 9)

move = value if value < 2 else value + 1

Mathematically, you want to select a random element in a set of 9 elements. 数学上,您想从9个元素中选择一个随机元素。 All you need to do is to identify the element 3 with 2, 4 with 3 and so on. 您需要做的就是用2标识元素3,用3标识4,以此类推。 In probability, this is what we call a random variable . 在概率上,这就是我们所说的随机变量

A random variable is defined as a function that maps the outcomes of unpredictable processes to numerical quantities. 随机变量定义为将不可预测过程的结果映射到数值量的函数。

This strategy of using a mapping is especially useful when your set is big and generating it would be costly, but the mapping rule is fairly simple. 当您的集合很大并且生成代价很高时,这种使用映射的策略特别有用,但是映射规则非常简单。

Improvement : 改善

It was pointed out by U9-Forward that in this case the mapping can be made slightly more efficient. U9-Forward指出,在这种情况下,可以使映射效率更高一些。 It suffices to map 2 to 10. 将2映射到10就足够了。

value =  random.randint(1, 9)

move = value if value != 2 else 10

Or do another way of conditioning like Olivier's answer: 或执行另一种类似Olivier回答的条件:

value =  random.randint(1, 9)
move = 10 if move==2 else move

Then move will never be 2 again. 然后move将不再是2

An obvious and easy interpretable path would be to exclude the 2 by a while-loop and just drawing numbers, using the function you mentioned, until the 2 gets not picked. 一个明显且容易解释的路径是使用您提到的功能通过while-loop2排除在外, while-loop仅绘制数字,直到不选择2 This is yet highly inefficient but a work-around you can reach with basic programming concepts. 这虽然效率很低,但是可以通过基本的编程概念来解决。

The more direct way would be to define your list more precisely, meaning without the 2 and making use of the random.choice function: 更直接的方法是更精确地定义列表,即不使用2并使用random.choice函数:

import random
print(random.choice([1, 3, 4, 5, 6, 7, 8, 9, 10]))

You can exclude number 2 using "while" 您可以使用“ while”排除数字2

move =  random.randint(1, 10)

while move == 2:
    move = random.randint(1, 10)

This code will generate random number until it won't be "2" 该代码将生成随机数,直到不会为“ 2”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM