如何从7个给定输入中选择随机输入?

时间:2015-10-22 14:30:02

标签: python

我正在创建一个彩票黑客机器,它获取过去7天的中奖号码并尝试从7中选择一个获胜者并随机抽取该选择的数量并打印结果。所有这些都是随机发生的。

#lottery hack

print "WELCOME TO LOTTERY HACK MACHINE!!!\n"
today = int(raw_input( "Please enter today's date: " ))
if today<=31:
    print "Please enter the 4-digit prize winning lottery number for the last 7 days"
    y = raw_input( "Enter 7 numbers separated by commas: " )
    input_list = y.split(',')
    numbers = [float(x.strip()) for x in input_list]

elif today>31:
    print "A month has only 31 days ;P"

2 个答案:

答案 0 :(得分:1)

您可以使用random.choice功能。它从您传递的序列中返回一个随机元素。

import random
print "WELCOME TO LOTTERY HACK MACHINE!!!\n"
today = int(raw_input( "Please enter today's date: " ))
if today<=31:
    print "Please enter the 4-digit prize winning lottery number for the last 7 days"
    y = raw_input( "Enter 7 numbers separated by commas: " )
    input_list = y.split(',')
    numbers = [float(x.strip()) for x in input_list]
    print random.choice(numbers)

elif today>31:
    print "A month has only 31 days ;P"

如果您要将整个列表随机播放而不是一次打印一个随机元素,则可以使用random.shuffle函数。

import random
print "WELCOME TO LOTTERY HACK MACHINE!!!\n"
today = int(raw_input( "Please enter today's date: " ))
if today<=31:
    print "Please enter the 4-digit prize winning lottery number for the last 7 days"
    y = raw_input( "Enter 7 numbers separated by commas: " )
    input_list = y.split(',')
    numbers = [float(x.strip()) for x in input_list]
    random.shuffle(numbers)
    print numbers

elif today>31:
    print "A month has only 31 days ;P"

正如评论中所阐明的那样,您需要一种结合这两种方法的方法。

import random
print "WELCOME TO LOTTERY HACK MACHINE!!!\n"
today = int(raw_input( "Please enter today's date: " ))
if today<=31:
    print "Please enter the 4-digit prize winning lottery number for the last 7 days"
    y = raw_input( "Enter 7 numbers separated by commas: " )
    input_list = y.split(',')
    numbers = [list(x.strip()) for x in input_list]
    choice = random.choice(numbers)
    random.shuffle(choice)
    print ''.join(choice)

elif today>31:
    print "A month has only 31 days ;P"

答案 1 :(得分:1)

Python随机有一个module。 以下是您可以使用它的方法:

import random
print(random.choice(numbers))

choice方法可以帮助您从序列中获取随机元素