簡體   English   中英

如何從7個給定輸入中選擇一個隨機輸入?

[英]How to choose a random input from 7 given input?

我正在創建一台彩票黑客機,該機將獲取最近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"

您可以為此使用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隨機播放,而不是一次打印一個隨機元素,則可以使用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"

Python有一個用於隨機的模塊 這是使用方法:

import random
print(random.choice(numbers))

choice方法為您完成了從序列中獲取隨機元素的工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM