选择带输入的多个随机整数

时间:2012-08-22 08:03:18

标签: python

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

4 个答案:

答案 0 :(得分: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)]

答案 1 :(得分:0)

myrands = [rand_int(1,10) for x in range(0,int(raw_input()))]

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

答案 2 :(得分: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

答案 3 :(得分:-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]