如何获得非重复随机整数

时间:2013-04-12 23:20:01

标签: python-3.x

我试图将0到25之间的数字分配到列表上的26个内容但不能重复我假设您将使用if和else语句但这是我到目前为止

def f():
    a=[0]*26
    for x in a:
        b=randrange(0,26)
        a[b]=randrange(0,26)
    return(a)
print(f()) 

1 个答案:

答案 0 :(得分:2)

列出数字0..25并将其随机播放:

>>> import random
>>> a = list(range(26))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 2
2, 23, 24, 25]
>>> random.shuffle(a)
>>> a
[11, 3, 17, 0, 20, 13, 24, 21, 4, 12, 14, 1, 22, 18, 5, 8, 6, 10, 9, 25, 23, 19,
 16, 7, 2, 15]