隨機和序列隨機選擇和樣本
import random
洗牌()
你可以使用 random.shuffle()
以可變和可索引的順序混合/隨機化專案。例如一個 list
:
laughs = ["Hi", "Ho", "He"]
random.shuffle(laughs) # Shuffles in-place! Don't do: laughs = random.shuffle(laughs)
print(laughs)
# Out: ["He", "Hi", "Ho"] # Output may vary!
選擇()
從任意序列中獲取隨機元素 :
print(random.choice(laughs))
# Out: He # Output may vary!
樣品()
像 choice
一樣,它從隨機序列中獲取隨機元素,但你可以指定多少:
# |--sequence--|--number--|
print(random.sample( laughs , 1 )) # Take one element
# Out: ['Ho'] # Output may vary!
它不會採用相同的元素兩次:
print(random.sample(laughs, 3)) # Take 3 random element from the sequence.
# Out: ['Ho', 'He', 'Hi'] # Output may vary!
print(random.sample(laughs, 4)) # Take 4 random element from the 3-item sequence.
ValueError:大於人口的樣本