確定,所以我寫產生這樣如何在Python中打印不是另一個數字的數字?
import random
randomNumber = random.randrange(1,4)
我怎樣才能使Python打印之間的範圍內的數的隨機數的碼(1,4),將永遠不會打印相同數量的「隨機數「變量?例如,說randomNumber選擇數字3.我想要第二個randomNumber選擇器打印1或2.我怎樣才能做到這一點?
確定,所以我寫產生這樣如何在Python中打印不是另一個數字的數字?
import random
randomNumber = random.randrange(1,4)
我怎樣才能使Python打印之間的範圍內的數的隨機數的碼(1,4),將永遠不會打印相同數量的「隨機數「變量?例如,說randomNumber選擇數字3.我想要第二個randomNumber選擇器打印1或2.我怎樣才能做到這一點?
爲了從列表中選擇k
項目,使用random.sample:
import random
x = range(1,4)
print(random.sample(x, k))
如果你想從所有的範圍(1,4)的項目, shuffle it,然後只需通過迭代洗牌列表:
import random
x = list(range(1,4)) # list is for Python3 compatibility
random.shuffle(x)
print(x)
# [2, 3, 1]
如果你想從一個範圍內獲得隨機值而不是重複以前的值,那麼你可以使用random.choice
每次迭代,然後從範圍中彈出項目並重復。
import random
seq = range(1, 4)
while len(seq) > 0:
ret = random.choice(seq)
seq.pop(seq.index(ret)) # pop result
print(ret)
如果要在一定範圍內隨機返回的數字而沒有重複任何號碼,您可以使用random.shuffle
作爲unutbu的答案。
如果你想被重複中只排除某些項目(如僅僅是第一),你可以使用一個set
和random.sample
:
x = set(range(1,4))
r = random.sample(x, 1)
x.remove(r) # we should never return r again
# these two calls might return the same number (but not r)
random.sample(x, 1)
random.sample(x, 1)
響應您的評論:
我的代碼看起來像這樣randomNumber = random.randrange(1,4)userChoice = raw_input(「Pick 1,2,3」)然後我想打印與userChoice或randomNumber不同的數字。讓我們把這個變量「不」
嘗試:
randomNumber = random.randrange(1, 4)
userChoice = raw_input("Pick 1, 2, or 3")
s = set([1,2,3]) - set([randomNumber, userChoice])
notPicked = random.sample(s, 1)[0] # this returns a one-element list, so [0] gets that one value
好吧,如果他們確實選擇和rand.randrange相同的數字,那麼這意味着notPicked變量現在可以選擇2個數字(或者至少這是我想要的發生) – user3528395
@ user3528395更新了答案 – Alec
你想避免重複_only_第一個號碼,或避免重複獲取返回的任何數字。 – Alec
我的代碼看起來像這樣randomNumber = random.randrange(1,4)userChoice = raw_input(「Pick 1,2,3」)然後我想打印與userChoice或randomNumber不同的數字。讓我們把這個變量稱爲「不」 – user3528395