如何在while循环中生成非重复随机数? (Python 3)

时间:2015-09-15 22:34:45

标签: python python-3.x random while-loop

到目前为止,我所拥有的是

import random
def go():
    rounds = 0
    while rounds < 5:
        number = random.randint(1, 5)
        if number == 1:
            print('a')
        elif number == 2:
            print('b')
        elif number == 3:
            print('c')
        elif number == 4:
            print('d')
        elif number == 5:
            print('e')
        rounds = rounds + 1
go()

并且输出结束了

的行
e
e
c
b
e

如何制作一个号码只使用一次,字母不重复? (例如某事)

a
e
b
c
d

提前致谢

1 个答案:

答案 0 :(得分:9)

random.sample(population, k)方法返回来自指定总长度k的唯一值的样本。

r = random.sample("abcde", 5)
for element in r:
    print(element)