如何在两个值之间随机选择? [英] How to choose randomly between two values?

查看:65
本文介绍了如何在两个值之间随机选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本上我试图让一段代码在两个值 -40 和 40 之间随机选择.

So basically I'm trying to get a piece of code to randomly choose between two values -40 and 40.

为此,我正在考虑使用古老的数学,例如 -

To do so, I was thinking of using good old mathematics like -

random_num = ((-1)^value)*40,其中 value = {1, 2}.

random_num = ((-1)^value)*40, where value = {1, 2}.

random_num,顾名思义应该是一个随机数.

random_num, as the name suggest should be a random number.

有什么帮助吗?

我正在使用 python,使用库的解决方案是可以接受的.

I am using python, solution using libraries is acceptable.

推荐答案

如果你想要一个介于 -40 和 +40 之间的随机整数值,那么

If you want a random integer values between -40 and +40, then

import random
random.randint(-40, 40)

https://docs.python.org/3.1/library/random.html#random.randint

如果您想选择 -40 或 +40,则

If you want to choose either -40 or +40, then

 import random
 random.choice([-40, 40])

https://docs.python.org/3/library/random.html#random.choice

如果你真的更喜欢选择 1 或 2 的实现,就像你的问题一样,那么在 random.choice 方法中插入这些值.

If you really prefer to go with your implementation of choosing either 1 or 2, as in your question, then plug in those values in random.choice method.

提供了上述解决方案,因为我觉得问题有些含糊.

Provided the above solutions, since I feel there is some ambiguity in the question.

这篇关于如何在两个值之间随机选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆