Python random 生成不重复的随机数

  • Post author:
  • Post category:python


Python random 生成不重复的随机数

先说结论:


random.sample(range(10), n)



random.sample(range(0, 10), n)


以上两条表示在

范围0-9内不包括10

生成n条随机数


random.randint(0, 10)


以上表示在

范围0-10内包括10

生成1条随机数

比如:

import random
test = random.sample(range(10), 10)
print(test)

输出 [4, 8, 3, 6, 9, 5, 2, 0, 1, 7]

test = random.sample(range(0, 10), 10)
print(test)

输出 [3, 0, 4, 9, 5, 1, 7, 6, 2, 8]

T = []
for i in range(100):
    test = random.randint(0, 10)
    if test not in T:
        T.append(test)
print(T)

输出 [8, 4, 9, 2, 5, 0, 10, 1, 3, 6, 7]


test = random.sample(range(0,10), 11)

报错 ValueError: Sample larger than population or is negative


test = random.sample(range(10), 11)

报错 ValueError: Sample larger than population or is negative



版权声明:本文为weixin_43499457原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。