首页 > 解决方案 > 这段代码中的“count”在审查一个单词时做了什么?

问题描述

好的,所以我在 Codecademy 结束了,我已经被这段代码困住了一段时间,我只是没有得到它。所以我最终只是得到了解决方案并试图理解它。但我并没有真正理解这一切。

代码是:

def censor(text, word):
  words = text.split()
  result = ''
  stars = '*' * len(word)
  count = 0
  for i in words:
    if i == word:
      words[count] = stars
      count += 1
  result =' '.join(words)

  return result

print censor("this hack is wack hack", "hack")

现在我认为 count 必须是索引(因为它说words[count] = stars),但我不明白他们为什么将其设置为整数(0)或添加一个,我猜它与设置位置有关文本中的审查,但如果有人能更好地向新手解释这一点,我将不胜感激,所以我不只是在不理解的情况下通过它。

提前致谢 :)

标签: pythonpython-2.7count

解决方案


我认为你复制代码错误的队友。我认为应该是这样的——

def censor(text, word):
  words = text.split()
  result = ''
  stars = '*' * len(word)
  count = 0
  for i in words:
    if i == word:
      words[count] = stars
    count += 1  # this line executes regardless of the if condition
  result =' '.join(words)

  return result

print censor("this hack is wack hack", "hack")

在这里count,它跟踪正在评估的单词的位置。如果这个词恰好等于被审查的词,它会正确地用星号替换这个词。现在你怎么知道这个词在列表中的什么位置?-计数


推荐阅读