Finding the index by searching for a string in a list
我目前正在阅读"python programming for the absolute初学者3",我有一个关于其中一个挑战的问题。
我正在创建一个单词混合游戏,它将从列表或元组中选择一个单词,混合该单词并要求用户猜测该单词。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | # Word Jumble # The computer picks a random word and then"jumbles" it # The player has to guess the original word import random # Create a sequence of words to choose from WORDS = ("python","jumble","easy","difficulty","answer","xylophone") # Pick one word randomly from the sequence word = random.choice(WORDS) # Create a variable to use later to see if the guess is correct correct = word # Create a jumbled version of the word jumble ="" while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] # Start the game print( """ Welcome to Word Jumble! Unscramble the letters to make a word. (Press the enter key at the prompt to quit.) """) print("The jumble is:", jumble) guess = input(" Your guess:") while guess != correct and guess !="": print("Sorry, that's not it.") guess = input("Your guess:") if guess == correct: print("That's it! You guessed it! ") print("Thanks for playing!") input(" Press the enter key to exit.") |
这是这本书的原始代码。挑战是在比赛中实施提示和得分系统。我有一个想法,创建另一个tuple各自的单词tuple和提示那里。IE:
1 2 3 4 5 6 | hints = ("*insert hint for python*", "*insert hint for jumble*", "*insert hint for easy*", "*insert hint for difficulty*", "*insert hint for answer*", "*insert hint for xylophone*") |
我想做的是找到random.choice单词的索引,这就是我尝试的。
1 2 | index = word.index(WORDS) print(index) |
我在想,这将与tuple单词的整数一起返回,并允许我使用以下命令打印提示:
1 | print(hints[index]) |
但是,我错了。这有可能吗?我让它起作用了,但是它是一长串if,elif语句,比如:
1 2 3 | if guess =="hint" or guess =="Hint" or guess =="HINT": if hint =="python": print(HINTS[0]) |
我知道有些人可能会说,"为什么你不坚持这个,因为它起作用了?"我知道我可以做到这一点,但我学习Python或编程的重点是了解如何以各种方式完成设置任务。
--此部分是次要的,不需要响应,除非您希望--
另外,我的评分系统如下,以防任何人对如何改进或是否做得好有想法。
想法是你的分数从100开始,如果你使用提示,你会损失50%的总分。每次猜测都会使总分减少10分。如果您的分数达到负数,它将被设置为0。我就是这样做的。
1 2 | score = 100 guesses = 1 |
这是在使用提示后添加的。
1 | score //= 2 |
在猜测之后。
1 | guesses += 1 |
最后,如果猜测是正确的。
1 2 3 4 5 6 7 8 | if guess == correct: print("That's it! You guessed it! ") score = score - (guesses - 1) * 10 if score <= 0: score = 0 print(" Your score is:", score) |
一如既往,我们非常感谢您的帮助。
如果你有:
1 | >>> WORDS = ("python","jumble","easy","difficulty","answer","xylophone") |
使用
1 2 | >>> WORDS.index('easy') 2 |
类似地:
1 2 3 4 5 | >>> word = random.choice(WORDS) >>> word 'answer' >>> WORDS[WORDS.index(word)] 'answer' |
你在你的问题中建议你看到一些没有意义的行为。如果你认为你所做的事情与我在这里所描述的大致相似,那么如果你能用一个具体的例子来更新你的问题,这个例子可以显示(a)你期望得到什么,(b)你实际得到什么,以及(c)一路上遇到的任何错误。
要从
1 | >>> WORDS.index(word) |