Python 不包括一个变量的随机数

Python random number excluding one variable

是否可以用一个随机数创建一个变量,除了一个存储在变量中的数字?

例如:

import random
x = raw_input("Number: ")
y = random.randint(1,6)

所以变量 x 永远不可能是 y

试试这个:

import random

x = int(raw_input("Number(1-6): ")) # note I made x an int

while True:
    y = random.randint(1, 6)
    if x != y: break

我建议您使用 random.choice 形式的号码列表,而不是您选择的号码

import random
x = raw_input("Number: ")
y = random.choice(range(1, x) + range(x+1, 6))

与其使用 random.randint(),不如生成一个可能值列表并删除不需要的值。然后在缩减列表上使用random.choice()

import random
x = int(input("Number: "))
numbers = list(range(1, 7))
numbers.remove(x)
y = random.choice(numbers)

演示:

>>> import random
>>> x = 5
>>> numbers = list(range(1, 7))
>>> numbers
[1, 2, 3, 4, 5, 6]
>>> numbers.remove(x)
>>> numbers
[1, 2, 3, 4, 6]
>>> random.choice(numbers)
6
>>> random.choice(numbers)
1
>>> random.choice(numbers)
2

如果您确定X是1到6之间的数字,您可以选择不包括X的范围。

import random
x = input("Number: ")
end  = 6
r = range(1,x) + range(x+1, end)
random.choice(r)

正如 在您的问题的评论中提到的,一个简单的 while 循环将是实现此目的的最简单方法:

import random
x = int(raw_input("Number: "))
y = random.randint(1,6)

while x == y:
    y=random.randint(1,6)

在 python 3 中跳过 idx 11 从 0..20

import numpy as np
range = np.concatenate([np.arange(0, 10, dtype=np.int), np.arange(11, 20, dtype=np.int)])
choice = np.random.choice(range)