在刽子手游戏的for循环中感到困惑?

时间:2018-04-20 19:43:53

标签: python

我引用的刽子手代码来自Invent Your Own Games with Python本书:

在显示游戏板的功能中,有一个for循环用一个由下划线组成的字符串替换为与secretWord相对应的正确的猜测字母:

    for i in range(len(secretWord)):
        if secretWord[i] in correctLetters:
            blanks = blanks[:i] + secretWord[i] + blanks[i+1]

我无法理解和可视化行blanks = blanks[:i] + secretWord[i] + blanks[i+1] 我们说secretWord = "otter"blanks = "_____"(五个下划线)。 for循环究竟是如何工作的?

3 个答案:

答案 0 :(得分:2)

for i in range(len(secretWord)):
    if secretWord[i] in correctLetters:
        # blanks = the underscores from 0 to i found in blanks
        # + the secret letter at index i in secretWord
        # + the underscores from i+1 to the end found in blanks
        blanks = blanks[:i] + secretWord[i] + blanks[i+1:]

示例:

blanks = _____ (5 underscores)
secretWord = Hi

lets assume that 'i' is in correct letters and 'h' is not
(loop 2 times since len('hi') == 2)
------------------------------------------------------
First iteration:

if 'h' in correctLetters (its not so skip):
------------------------------------------------------
Second iteration:

'i' is in correctLetters

blanks = __ (underscores from 0 to 1 in blanks) 
   + 'i' (the letter at secretWord[1]) 
   + __ (blanks[2:onward] - the rest of the underscores ignoring the one where the letter goes)

将相同的逻辑应用于像Otter这样的较长的单词,会发生的事情是它将继续使用在correctLetters中找到的来自secretWord的字母替换空白中的下划线。 secretWord otter和blanks = _____的结果意味着blanks = otter

答案 1 :(得分:2)

让我们想象你的字母't'是正确的。 所以correctLetters = ['t'],我们通过我们的秘密词,看看t出现在哪里。

对于i = 0没有任何反应,'o'不在我们的正确信中 对于i = 1,我们得到't',它是correctLetters的一部分,所以我们能够用空白来做魔术:

|空格[:i]获取字符串直到位置i = 1,所以这里:'_'
secretWord [i]给你't',因为i = 1
空白[i + 1]给你所有其余的字符串,从位置i + 1 = 2开始 - > ___

总的来说,在这次迭代之后你有_t___。

你我们会再用另一个t(现在i = 2)做同样的事情,你将会: blanks = _tt __

然后很容易猜到奥特,对吧;)

答案 2 :(得分:1)

for i in range(len(secretWord)):
# i is index of secretword
  if secretWord[i] in correctLetters:
  # checking if letter secretWord[i] is in correctletters
  # if it is in, replace _ in blacks  to secretWord[i]
  # recreate blank list by using everything before index i, secretWord[i], and everything after index i
    blanks = blanks[:i] + secretWord[i] + blanks[i+1]