python - 这段代码中的“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)或添加一个,我猜它与设置位置有关文本中的审查,但如果有人能更好地向新手解释这一点,我将不胜感激,所以我不只是在不理解的情况下通过它。
提前致谢 :)
解决方案
我认为你复制代码错误的队友。我认为应该是这样的——
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
,它跟踪正在评估的单词的位置。如果这个词恰好等于被审查的词,它会正确地用星号替换这个词。现在你怎么知道这个词在列表中的什么位置?-计数
推荐阅读
- javascript - 如何让命运之轮平稳地停在特定的路段
- c - C 中的 strtok 因 char 指针而崩溃
- tensorflow - tf.function 是否也为它调用的其他函数创建图形?
- python - ValueError:条件数组必须与自身的形状相同
- r - 如何整理包含多个信息的列的数据集-Sample data put?
- android - 带有动画的 Android 矩阵后标度
- javascript - 里面的console.log
零件 - c++ - 定义中的显式特化导致错误:非命名空间范围内的显式特化
- php - 如何在多数组中回显单个值
- python - 如何正确使用 time.time()