python字符串索引和列表索引_关于python:通过搜索列表中的字符串来查找索引

我目前正在阅读"python programming for the absolute初学者3",我有一个关于其中一个挑战的问题。

我正在创建一个单词混合游戏,它将从列表或元组中选择一个单词,混合该单词并要求用户猜测该单词。

# 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:

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单词的索引,这就是我尝试的。

index = word.index(WORDS)

print(index)

我在想,这将与tuple单词的整数一起返回,并允许我使用以下命令打印提示:

print(hints[index])

但是,我错了。这有可能吗?我让它起作用了,但是它是一长串if,elif语句,比如:

if guess =="hint" or guess =="Hint" or guess =="HINT":

if hint =="python":

print(HINTS[0])

我知道有些人可能会说,"为什么你不坚持这个,因为它起作用了?"我知道我可以做到这一点,但我学习Python或编程的重点是了解如何以各种方式完成设置任务。

--此部分是次要的,不需要响应,除非您希望--

另外,我的评分系统如下,以防任何人对如何改进或是否做得好有想法。

想法是你的分数从100开始,如果你使用提示,你会损失50%的总分。每次猜测都会使总分减少10分。如果您的分数达到负数,它将被设置为0。我就是这样做的。

score = 100

guesses = 1

这是在使用提示后添加的。

score //= 2

在猜测之后。

guesses += 1

最后,如果猜测是正确的。

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)

一如既往,我们非常感谢您的帮助。

你的问题是什么?

如果你有:

>>> WORDS = ("python","jumble","easy","difficulty","answer","xylophone")

使用index方法,可以得到该单词在列表中的数字位置:

>>> WORDS.index('easy')

2

类似地:

>>> word = random.choice(WORDS)

>>> word

'answer'

>>> WORDS[WORDS.index(word)]

'answer'

你在你的问题中建议你看到一些没有意义的行为。如果你认为你所做的事情与我在这里所描述的大致相似,那么如果你能用一个具体的例子来更新你的问题,这个例子可以显示(a)你期望得到什么,(b)你实际得到什么,以及(c)一路上遇到的任何错误。

哈哈,我把单词放错地方了。谢谢您!

我很抱歉没有把错误弄清楚,我忘了我没有复制/粘贴它。它说:typeerror:无法将"tuple"对象隐式转换为str

要从WORDS中获取单词的索引,请使用:

>>> WORDS.index(word)

真的。。。哈哈,真不敢相信这么简单。我只是把单词放错了地方。

@麦克德里比正好是我们中最好的):祝你学习Python好运!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值