[英]How to choose a random input from 7 given input?
I'm creating a lottery hack machine which gets the winning numbers of the last 7 days and tries to select a winner from the the 7 and shuffle the numbers of that selection and print the result. 我正在创建一台彩票黑客机,该机将获取最近7天的中奖号码,并尝试从7中选择一名中奖者,并洗净该选择的号码并打印结果。 All this occurs at random.
所有这些都是随机发生的。
#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"
You can use the random.choice
function for this. 您可以为此使用
random.choice
函数。 It returns a random element from the sequence you pass it. 它从您传递的序列中返回一个随机元素。
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"
If you want to shuffle the entire list in place instead of printing random elements from it one at a time, you can use the random.shuffle
function. 如果您希望将整个列表按
random.shuffle
随机播放,而不是一次打印一个随机元素,则可以使用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"
As clarified in the comments, you need an approach that combines these two approaches. 正如评论中所阐明的,您需要一种将这两种方法结合在一起的方法。
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.