在另一个变量中使用变量

时间:2014-10-16 14:26:23

标签: python variables

我要做的是让用户输入一个名称,然后程序会接受该名称,将单词Move添加到其中,然后抓取一个名为*name*Move的集合。 / p>

到目前为止,这是我的代码,以及**中我想要做的事情:

fredMove = set(["move1","move2","move3","move4"])  #different data
joeMove = set(["move","move","move3","move4"])     #for each name
chrisMove = set(["move1","move2","move3","move4"]) #this is just
timMove = set(["move1","move2","move3","move4"])   #easier to write out
#I have many more lists, as well

name = input("What is the name you are looking for? ").lower

def moveChecking(move1,move2,move3,move4,name):
    if (move1 not in *name*Moves):
        print("Move 1 not found!")
    if (move2 not in *name*Moves):
        print("Move 2 not found!")
    if (move3 not in *name*Moves):
        print("Move 3 not found!")
    if (move4 not in *name*Moves):
        print("Move 4 not found!")

move1 = input("Enter move 1 = ")
move2 = input("Enter move 2 = ")
move3 = input("Enter move 3 = ")
move4 = input("Enter move 4 = ")

moveChecking(move1,move2,move3,move4,name)

以某种方式做我想做的事情让我避免为每个人的名字创建moveChecking()

3 个答案:

答案 0 :(得分:2)

使用字典。

moves = {
    "fred":  set(["move1","move2","move3","move4"])
    "joe":   set(["move1","move2","move3","move4"])
    "chris": set(["move1","move2","move3","move4"])
    "tim":   set(["move1","move2","move3","move4"])
}

name = input("What is the name you are looking for?")
for i in range(1, 5):
    move = input("Enter move {} = ".format(i))
    if move not in moves[name]:
        print("Move {} not found!".format(i))

答案 1 :(得分:1)

创建移动集的字典,然后按名称

访问它们
moveDict = {'fred': fredMove, 'joe':joeMove } #etc

然后在moveChecking中使用

if move1 not in moveDict[name]:
    #...

答案 2 :(得分:1)

他们是很多很多丑陋的方式来做你想要的,因为你已经描述了它(基本上在模块级别做getattr),但这似乎更像是一个糟糕的设计案例。为什么不使用dictionary,而不是key作为名称而value作为集合,而不是将一堆集合直接分配给命名变量? EX:

moves = {'timMove':set(["move1","move2","move3","move4"]),
 ....}

然后你可以简单地设置移动设置:

try:
    move_set = moves[name]
except KeyError:
     # handel a bad name here