【发布时间】:2018-11-24 04:51:48
【问题描述】:
my_string = """Strings are gameon amongst gameon the most popular data types in Python. We can create the strings by enclosing characters briton in quotes. Python treats briton single quotes the same as double quotes."""
def count_words(string):
for word in string.split():
if word.endswith("on") == True:
print(word,":",string.count(word))
string = string.replace(word,'')
count_words(my_string)
如果它们以“on”结尾,我想打印一个单词中的所有单词及其出现。我得到了类似的东西
gameon : 2
gameon : 0
briton : 2
Python : 2
briton : 0
即使在删除这个词之后也是如此。 为什么会重复?
编辑:我不能使用任何模块。只有逻辑。
【问题讨论】:
-
使用字典存储字符串及其计数,不要删除循环内的项目。
-
它是“重复的”,因为您每次在迭代时看到这个词时都会计算
gameon(即两次 - 第一次有 2 个,第二次将它们全部替换为空字符串,所以字符串中有0,但列表当然不受影响) -
你应该使用正则表达式!!此外,字符串是不可变的。您不能循环遍历一个并在执行此操作时对其进行修改。
string = string.replace(word,'')只是改变了局部变量string是什么,它不会改变my_string本身...也不会改变你使用for word in string.split()迭代的值,这是一个(拆分)副本字符串本身。 -
非常感谢你们! :D