Python,在字母列表中查找多个索引

时间:2013-11-18 02:21:34

标签: python loops indexing

所以我刚刚开始学习python并正在为一个项目创建一个刽子手游戏。我被困了。我给你一些背景。

我得到程序去除字母表中的字母,并将它们添加到正在猜测的单词的空白处,但它只会找到第一个字母的索引。所以我要说的是,我试图猜测这个词是安全的。现在让我说我猜字母f。它返回f _ _ _ _ _ _ _而不是f _ _ _ _ _ f _。在我看来,一旦找到列表中的第一个字母实例并在那里打破,for循环就会停止。我需要找到并显示这封信的所有实例。

代码:

def makechoice(list)
    # defines the word trying to be guessed as a list of letters
    Global listword
    #defines the amount of blanks in listword as a list "_ "
    global blanks
    #user input to guess a letter
    current = raw_input("Please enter your guess:")
    for a in listword:
        if a == current:
            t = listword.index(a)
            #puts the letter and a blank in place of the unoccupied space if it is a match.
            blanks[t] = str(listword[t]) + " "

不,只是我或不应该循环列表中的所有字母,如果它发现2“f”显示它们两者。请有人帮忙。我做过研究,似乎无法弄清楚我错过了什么。

4 个答案:

答案 0 :(得分:5)

.index()返回给定字符的第一个索引。如果单词具有多次相同的字符,则它将仅返回第一个索引(除非您明确指定起始偏移量)。

如果在迭代期间需要访问索引,则应使用enumerate()

for i, x in enumerate(listword):
    # i is the index, x is the character
    if x == current:
        blanks[i] = listword[i] + " "

答案 1 :(得分:1)

您可以使用index函数中的第二个参数来指定搜索字符的起始索引。

data = "Welcome to ohio"
t = -1
while True:
    try:
        t = data.index("o", t + 1)
        print t
    except ValueError:
        break

<强>输出

4
9
11
14

答案 2 :(得分:1)

或在重新包装中使用finditer:

import re
[x.start() for x in re.finditer("f", "failsafe")]

输出:[0,6]

答案 3 :(得分:0)

在你打印单词

之前,我会留出多余的空格
>>> listword = "failsafe"
>>> blanks = list('_' * len(listword))
>>> guess = 'f'
>>> for i, j in enumerate(listword):
...     if j == guess:
...         blanks[i] = j
... 
>>> print " ".join(blanks)
f _ _ _ _ _ f _