我正在尝试编写以下猜词游戏,但出现类型错误。如何解决?谢谢!
import random
Dictionary = {"fruits":"watermelon", "buildings": "apartment", "mammal": "horse", "occupation": "fireman"}
def choose_word():
hint, chosen_word = random.choice(Dictionary.items())
print("Hint: " + hint)
blank = []
for letter in chosen_word:
blank.append("_")
print("".join(blank))
return chosen_word
答案 0 :(得分:1)
即使您在代码段的最后一行有错别字,我也不认为修复它会起作用。所以试试这个。
import random
Dictionary = {"fruits": "papaya", "buildings": "apartment", "mammal": "horse"}
def choose_word():
hint, chosen_word = random.choice(list(Dictionary.items()))
print("Hint: " + hint)
choose_word()
此处 Dictionary.items()
返回键值对的元组。对于 random.choice()
,我们选择了一个这样的元组。然后我们将相应的键值分别解包到 hint
和 chosen_word
。