I created this code and it works fine, but I think it's ugly. Could you show me a better way to create a list of three different random numbers from 1 to 9?
class Baseball_Engine(object):
def __init__(self):
self.count = 0
self.random_number_list = [0, 0, 0]
while self.count < 3:
random_number = random.randint(1, 9)
self.random_number_list[self.count] = random_number
if self.random_number_list[self.count - 1] != random_number and self.random_number_list[self.count - 2] != random_number:
self.count += 1
print self.random_number_list
-
1\$\begingroup\$ Please check your indentation. \$\endgroup\$200_success– 200_success2016年07月15日 03:25:15 +00:00Commented Jul 15, 2016 at 3:25
1 Answer 1
Without dwelling too deep into your code there are a few alternatives. After a very quick google search, I stumbled upon this question on SO.
They propose two different solutions.
import random
print random.sample(xrange(1, 10), 3)
This will create three distinct numbers with values ranging from 1 to 9. If you do not want the three numbers to be different, you could try the following
import random
print [random.randrange(1,10) for _ in range(3)]