我有一个查询只返回最后的结果,所以这是我的代码:
import random
def Step_1():
Start_Game = raw_input("Enter \'Start' to continue \n")
if Start_Game == 'start':
print "Let the Lottery begin"
else:
return Step_1()
#-------------------------------------------------------------------
def Step_2():
random_list = []
for i in range(10):
while len(random_list) < 6:
random_number = random.randint(1,59)
while random_number not in random_list:
random_list.append(random_number)
print random_list
Step_1()
Step_2()
当我运行它时,它给我以下结果,
Enter 'Start' to continue
start
Let the Lottery begin
[56]
[56, 20]
[56, 20, 32]
[56, 20, 32, 2]
[56, 20, 32, 2, 23]
[56, 20, 32, 2, 23, 30]
但是我怎样才能显示最后生成的结果并丢弃之前的5.我知道我需要在Step_2函数中更改最后一位“print”,但是我需要添加什么?
谢谢。
答案 0 :(得分:0)
一个班轮:
random.sample(range(1, 59), 6) # genrates 6 unique random no's in the range
要修改现有代码,请使用列表存储以前生成的随机编号
def Step_2():
random_list=[]
for i in range(6):
random_number = random.randint(1,59)
while random_number in random_list:
random_number = random.randint(1,59)
print random_number
list.append(random_number )
答案 1 :(得分:0)
对于你的step2()函数,你可能想要使用while循环,因为你真的不知道,在你有6个唯一数字之前需要生成多少个随机数。
def step2():
# Declare an empty list to hold the random numbers
numbers = []
# While we do not have 6 numbers in our list
while len(numbers) < 6:
# Generate a random number
rndnum = random.randint(1,59)
# If that random number is not yet in our list
if rndnum not in numbers:
# Append it to the list
numbers.append(rndnum)
return numbers