0

我一直在努力解决这个问题。我想输入一个 1 到 5 之间的数字。例如,如果我选择输入数字 3,我想从 1 到 10 之间的数字类别中随机选择 3 个数字。

4

4 回答 4

0

一个简单的方法:

from random import choice
list_of_numbers = range(11)[1:] # the 1: drops the zero
choice(list_of_numbers) # picks a random number from the list
于 2012-08-22T08:44:06.110 回答
0
import random
random.seed()
a = 1
b = 10
randList = []
for x in range(3):
    # random integer N such that a <= N <= b
    randList.append(random.randint(a, b))

或者更好:

import random
random.seed()
a = 1
b = 10
randList = [random.randint(a,b) for x in range(3)]
于 2012-08-22T08:08:03.303 回答
0
myrands = [rand_int(1,10) for x in range(0,int(raw_input()))]

myrands是 1 到 10 之间的随机数列表,长度由用户输入确定。

于 2012-08-22T08:14:06.123 回答
-1

这种东西可以工作......

In [84]: user_input = raw_input("Enter a number between 1 to 5 :")
Enter a number between 1 to 5 :3

In [85]: selected_elem = []

In [86]: while len(selected_elem) < int(user_input):
   ....:         random_elem = random.randrange(1, 10, 1)
   ....:         if random_elem not in selected_elem:
   ....:                 selected_elem.append(random_elem)
   ....:

In [87]: print selected_elem
[1, 2, 4]
于 2012-08-22T08:09:50.370 回答