随机和序列随机选择和样本
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:大于人口的样本