如何使用python生成20个唯一的随机数?

时间:2015-07-27 08:24:16

标签: python

我刚刚开始学习编程。当我开始章节时,我开始遇到问题。最大的问题之一就是当我面临一个用python生成随机数的问题时。“生成20个随机唯一数字并对它们进行排序无论是按升序还是按降序排列“。我已经对如何做到这一点进行了研究,但我现在很困惑并想到放弃。任何人都可以给我一个例子,告诉我如何做到这一点和解释对此。

4 个答案:

答案 0 :(得分:2)

>>> import random
>>> var = random.sample(range(1, 10000), 20)
>>> var
[4691, 1789, 9473, 4042, 8423, 5021, 2627, 2739, 6337, 4963, 5772, 9180, 2788, 1197, 1276, 3393, 7748, 9448, 3618, 1835]
>>> var.sort()
>>> var
[1197, 1276, 1789, 1835, 2627, 2739, 2788, 3393, 3618, 4042, 4691, 4963, 5021, 5772, 6337, 7748, 8423, 9180, 9448, 9473]

首先,您从给定范围生成20个数字,然后使用sort()

进行简单排序

答案 1 :(得分:0)

您可以使用随机模块:

>>> from random import random
>>> lst = sorted([random() for x in range(20)])

响应:

[0.023779304268199186, 0.09302269288440945, 0.09832361922809707, 0.25242017515656756, 0.3506703186883351, 0.35105790921933866, 0.36493338390569785, 0.4758485640689768, 0.5224413002068954, 0.5794797893890528, 0.5826667916581931, 0.6050065111356167, 0.6283016356471698, 0.6709347774971688, 0.680474965216515, 0.6871898214051998, 0.7105349504105246, 0.7362770892874505, 0.8778691065354278, 0.8980497474361055]

或者,如果您想确保没有重复:

from random import randint
a_set = set()
while True:
    a_set.add(randint(0, 1000))
    if len(a_set)==20:
        break
lst = sorted(list(a_set))
print(lst)

结果:

[6, 94, 132, 258, 370, 389, 407, 462, 468, 528, 637, 640, 677, 692, 704, 872, 875, 883, 889, 913, 999]

答案 2 :(得分:0)

请尝试以下代码:

import random
startValue = 5
endValue = 150
rangeOfNumbers = xrange(startValue, (endValue + 1))
count = 10
randomNumList = random.sample(rangeOfNumbers, count)
print "Unsorted list of random numbers", randomNumList
randomNumList.sort()
print "Sorted list of random numbers", randomNumList

您将获得以下输出:

Unsorted list of random numbers [131, 138, 137, 22, 23, 69, 21, 66, 12, 83]
Sorted list of random numbers [12, 21, 22, 23, 66, 69, 83, 131, 137, 138]

答案 3 :(得分:-1)

import random


def make_list_distinct(_l, wanted_lenght=20):
    current_list = list(set(_l))
    _ = 20 - len(current_list)
    if _ > 0:
        current_list = current_list + [random.randint(1, 2000) for i in range(_)]
        make_list_distinct(_l = current_list)
    else:
        final_list = sorted(current_list)
        print(final_list)

if __name__ == '__main__':

    #a = [random.randint(1, 2000) for i in range(20)]
    a = [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
    make_list_distinct(a)