简体   繁体   English

Function 用于随机 integer 的两个数字而不是数字之间

[英]Function for random integer of two numbers and not between to numbers

Maybe very basic question but is there a random function that gives me the integers eg.也许是非常基本的问题,但是否有一个随机的 function 给我整数,例如。 1 or 6. 1 或 6。

I don't mean random.randint(1, 6).我不是说 random.randint(1, 6)。 I want either 1 or 6, no numbers in between.我想要 1 或 6,中间没有数字。

import random

random.choice((1, 6))

This will return a random selection from the tuple you pass in. Since the tuple only contains the numbers 1 and 6, those are the only possible outputs.这将从您传入的元组中返回一个随机选择。由于元组仅包含数字 1 和 6,因此这些是唯一可能的输出。

You can use this trick:你可以使用这个技巧:

random.randint(0, 1) * 5 + 1

How it works:这个怎么运作:

First, you choose a number from 0 or 1. Second, you multiply it by 5 which will result to either 0 or 5. At last you add 1 which is going to change 0 or 5 to 1 or 6首先,从 0 或 1 中选择一个数字。其次,将其乘以 5,得到 0 或 5。最后,加上 1,将 0 或 5 变为 1 或 6

Here is a JavaScript version of the expression that randomly gives you either 1 or 6:这是表达式的 JavaScript 版本,它随机给出 1 或 6:

1 + Math.floor(Math.random() * 2) * 5

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

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