【发布时间】:2016-06-15 11:34:42
【问题描述】:
我有什么方法可以指定我想要的“ben Stiller”或“bill murray”的值吗?
我知道我不能做 random.choice(ben_stiller.values()):
我还更改了字典,所以关键是电影的名称,现在可以完美运行。
^
import random
last_man = {
'Mark Walberg': '1',
'Ben Stiller': '2',
'Bill Murray': '3',
}
markymark = {
'movie': 'The martian',
'movie': 'The Departed',
'movie': 'XYZ'
}
ben_stiller = {
'movie': 'Meet the parents',
'movie': 'Something about mary',
'movie': 'dunno'
}
bill_murray = {
'movie': 'Life Aquatic',
'movie': 'rushmore',
'movie': 'Groundhogs day'
}
print "There are three actors, one will be chosen randomly"
print "You have to name as many movies as they have been in"
print "If you get one wrong, you lose, you hae three chances, and must get one correct"
random.choice(last_man.keys())
print "The actor randonly chosen is: ", random.choice(last_man.keys())
guesses_taken = 0
while guesses_taken <= 3:
guess = raw_input(': ')
guesses_taken = guesses_taken + 1
if guess == random.choice(bill_murray.keys()):
print "you won in %s guesses" % guesses_taken
print guesses_taken
elif guess == random.choice(ben_stiller.keys()):
print "you won in %s guesses" % guesses_taken
print guesses_taken
elif guess == random.choice(markymark.keys()):
print "you won in %s guesses" % guesses_taken
print guesses_taken
elif guess != random.choice(markymark.keys()):
print "You lost"
print guesses_taken
else:
print "you lose"
exit(0)
【问题讨论】:
-
您可能需要重新考虑一下字典的工作原理。字典每个键只能有一个值。在字典文字的情况下,最后一个获胜,例如
bill_murray仅包含{'movie': "Groundhogs day"}。在您的情况下,keys()始终返回['movie']。 -
您在
if语句末尾缺少: -
... 和 : 在所有 elif 语句的末尾...。了解版本控制,以便在破坏代码时发现差异。
-
回复:'现在可以忽略这个'。如果我是你,我会删除这个问题。特别是当您编辑代码以纠正问题时:)
-
我实际上在工作版本中,有电影名称的键和电影的值。有什么办法可以做 random.choice(bill_murray.values()): ?我知道这不起作用,但我怎样才能检索到值?我想我可以使用密钥来生成它的值。
标签: python dictionary random