如何随机决定变量的变量?

时间:2014-08-07 21:38:07

标签: python random

所以我们有一个学校项目来制作一个程序,询问用户是从52平台挑选一张随机卡还是模拟抛硬币 - 头或尾。我有一个测试版工作,但我正在研究如何使该程序更有效。基本上,该程序将元组“卡”和“硬币”设置为所有可能的类型,因此对于硬币,头部和尾部以及卡片,52种不同的卡片。

程序的以下部分将变量“choice”设置为卡片或硬币

    while choice!='card' and choice!='coin':
            choice=input("Pick a card or toss a coin (card/coin)?: ")
            if choice!="card" and choice!="coin":
                print("Please enter either 'card' or 'coin'...")
                time.sleep(2)

接下来我希望能够根据'choice'的值从任一元组返回一个值,而不使用if和if语句,具体如下:

    print("The ",choice," picked at random is... ",random.choice("Either card, or coin"),"!")

我该怎么做?谢谢,布兰登。

完整计划:

#importing modules used in program
import time
import random

#creating duples for possible cards and coins
cards=["Ace of spades","King of spades","Queen of spades","Jack of spades","10 of spades","9 of spades","8 of spades","7 of spades","6 of spades","5 of spades","4 of spades","3 of spades","2 of spades","Ace of diamonds","King of diamonds","Queen of diamonds","Jack of diamonds","10 of diamonds","9 of diamonds","8 of diamonds","7 of diamonds","6 of diamonds","5 of diamonds","4 of diamonds","3 of diamonds","2 of diamonds","Ace of clubs","King of clubs","Queen of clubs","Jack of clubs","10 of clubs","9 of clubs","8 of clubs","7 of clubs","6 of clubs","5 of clubs","4 of clubs","3 of clubs","2 of clubs","Ace of hearts","King of hearts","Queen of hearts","Jack of hearts","10 of hearts","9 of hearts","8 of hearts","7 of hearts","6 of hearts","5 of hearts","4 of hearts","3 of hearts","2 of hearts"]
coin=["Heads","Tails"]

#setting variable 'repeat' to 'y' to start the mainloop of the program
repeat="y"
while repeat=="y":

    #blanking the repeat and choice variables so they can be reset later
    repeat=""
    choice=""

    #won't allow the user to continue until either 'card' or 'coin' is entered
    while choice!='card' and choice!='coin':
        choice=input("Pick a card or toss a coin (card/coin)?: ")
        if choice!="card" and choice!="coin":
            print("Please enter either 'card' or 'coin'...")
            time.sleep(2)


    print("The ",choice," picked at random is... ",random.choice(card),"!")


    #won't allow the user to continue until either 'y' or 'n' is entered
    while repeat!="y" and repeat!="n":
        repeat=input("Go again..? (y/n): ")
        if repeat!="y" and repeat!="n":
            print("Please enter either 'y' for yes or 'n' for no...")
            time.sleep(2)

#ending of the program
print("Goodbye!")
time.sleep(2)

2 个答案:

答案 0 :(得分:2)

实现这一目标的最简单方法是使用元组字典:

items = { 'coin': coin,
          'card': cards }

然后,在choice循环正确设置while之后,使用用户提供的单词作为键从字典中选择正确的列表,然后将其传递给{ {1}}:

random.choice

答案 1 :(得分:0)

我确定这是你要问的问题,但如果您正在谈论的元组是('coin', 'card'),那么您可以执行以下操作:

import random

test = ('coin', 'card')
test[random.randint(0, 1)]

这将随机选择两个选项中的一个。