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

标签 python python-2.7

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

这是这部分代码:

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/

相关文章:

python - 将 DataFrame 导出和导入到 Access 文件 (.mdb)

python - PGU HTML Renderer 无法呈现大多数网站

Python 日志记录如何跟踪日志中的主机名?

java - 带有 Endpoints Python 的 Android 客户端

python - Django 中的 AttributeError : 'NoneType' object has no attribute 'startswith' while makemigrations with manage. py

python - Django模型和mptt集成

python - 计算一个元素在 python 列表中连续出现 n 次的次数

python - 将手动安装的 OpenSSL 1.1.0e 链接到 python2.7

python - 在Python中按特定值对JSON进行排序

python - BeautifulSoup4 无法在我的托管服务器上运行