gpt4 book ai didi

python - in 语句仅对 python 中的列表起作用一次

转载 作者:太空宇宙 更新时间:2023-11-03 15:52:07 25 4
gpt4 key购买 nike

我正在制作一个简单的基于文本的刽子手游戏,我想检查用户输入的字母是否是包含用户应该猜测的单词的字符的列表的一部分。

这是这部分代码:

while True:
print "Guess a letter / The word (%d attempts remaining.)" % attempts
guess = raw_input()
if len(guess) == 1:
if guess in chars:
blankslist[chars.index(guess) * 2] = guess
blanks = "".join(str(x) for x in blankslist)
print blanks
else:
print "Nope!"
attempts -= 1
if attempts <= 0:
print "Game Over! The word was %s" % chosen_word
break

elif len(guess) == len(chosen_word):
if guess == chosen_word:
print "Congrats, you won with %d attempts left!" % attempts
else:
print 'Oh no, you lost... The correct word was "%s".' % chosen_word
break

else:
print("Input a single letter")

但是,对于包含重复字母的单词,例如“hippopotamus”,它只会检测到一个“p”。我怎样才能让它检测到两者?

编辑:为提问者添加了整个循环。

最佳答案

.index(guess) 仅返回它找到的第一个索引。

您可以使用类似的方法来获取所有索引:

positions = [i for i, char in enumerate(chars) if guess == char]

然后循环遍历这个列表:

for p in positions:
blankslist[p * 2] = guess

关于python - in 语句仅对 python 中的列表起作用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41191716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com