【问题标题】:Python, finding more than one index in a list of lettersPython,在字母列表中找到多个索引
【发布时间】:2013-11-18 02:21:34
【问题描述】:

所以我刚刚开始学习 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]) + " "

不,只是我,还是不应该循环遍历 listword 中的所有字母,如果找到 2 个“f”,则同时显示它们。请有人帮忙。我进行了研究,但似乎无法弄清楚我错过了什么。

【问题讨论】:

标签: python loops indexing


【解决方案1】:

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

当您需要在迭代期间访问索引时,您应该使用enumerate()

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

【讨论】:

  • 不,不会。我们可以使用index函数中的第二个参数。请检查我的答案。
  • 在这种情况下,它返回给定偏移后字符的第一个索引。找到第一次出现后它仍然返回。
  • 是的。但是it will only ever return the first index 可能会让人们不这么认为。
  • 我使用了下面的答案,效果很好。我也要测试这个。你能解释一下 enumerate() 吗?不知道我明白它在做什么。它只是将列表位置更改为其索引值吗?
  • enumerate 将允许您跟踪当前循环索引,这意味着您不再需要使用listword.index() 来查找您的进度。如果listword"hello",则在循环的第一次迭代中i=0, x='h',在第二次循环中i=1, x='e' 等等。然后您可以随意使用ix
【解决方案2】:

您可以使用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

【讨论】:

  • 我首先使用了这个答案,并且效果很好。我只是将它改编为我的代码。非常感谢,真的有帮助!
  • @user3003061 欢迎您。请考虑接受对您有最大帮助的答案。 meta.stackexchange.com/a/5235/235416
【解决方案3】:

或者在 re 包中使用 finditer:

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

输出:[0, 6]

【讨论】:

    【解决方案4】:

    在您打印单词之前,我会保留这些多余的空格

    >>> 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 _
    

    【讨论】:

    • 感谢您的帮助。我在上面得到了答案,但我真的很喜欢blanks = list("_" * len(listword))。我为 x in range len (listword + 1) 做了一个,这确实有助于清理我的代码。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多