首页 > 解决方案 > 我无法理解变量在 for 循环之前的作用

问题描述

我是 python 新手,我无法理解此 return 语句中“for”之前的变量的作用。我从这个问题中得到了这个代码的一个稍微修改过的版本

word = "boom"

def find_all(word, guess):
    return [i for i, letter in enumerate(word) if letter == guess]

我知道该函数正在获取用户在单词“boom”中猜测的字母的每一次出现,为索引创建“i”,为枚举函数即将给出的值创建“字母”。最后说明如果单词中的字母等于单词中的猜测,就会发生这种情况。

什么是

i for i

不过呢?我在上面找不到任何东西,当我把它拿出来时,它会破坏代码。有没有办法在退货中写这个?

我修改后的代码然后在状态

board = "_" * len(word)
listed_board = list(board)

while board != word:
    guess = input("Input a letter here ").lower()
    if guess in word:
        indices = find_all(word, guess)
        print(indices)
        listed_board = list(board)
        for i in indices:
            listed_board[i] = guess
            board = "".join(listed_board)
        print(listed_board)

我唯一不明白的另一部分是它在说什么

listed_board[i] = guess

这是在做什么?在listed_board上,此时它只是下划线,那么它是如何定位插入单词的正确位置并将其设置为用户猜测的呢?

感谢回复,谢谢!

标签: pythonloopsreturnenumerate

解决方案


好的,这是您的代码的工作方式:

word = "boom"

def find_all(word, guess):
    return [i for i, letter in enumerate(word) if letter == guess]

enumerate(word)创建新的可迭代对象。来自的每个字母'boom'都有自己的索引:[(0, 'b'), (1, 'o'), (2, 'o'), (3, 'm')]. 现在for循环遍历这个新对象,其中i等于索引(来自上面列表的数字),并且letter(变量)等于字母(来自列表的值)。因此,此函数将返回索引列表供您猜测。如果猜测相等'b',它将返回[0], 因为'o'它将是[1, 2], for 'm', [3],否则此列表将为空。

更进一步:

while board != word:
    guess = input("Input a letter here ").lower()
    if guess in word:
        indices = find_all(word, guess)  # This will return all index where 'guess' is equal to letter from world. For example for word='foo', guess='o' it will return [1,2]
        print(indices)
        listed_board = list(board)
        for i in indices:  # for each index you have found:
            listed_board[i] = guess  # replace '_' with correct letter (guess)
            board = "".join(listed_board)  # change list to string
        print(listed_board)

希望这段代码现在对你来说更明显。


推荐阅读