题目
统计下这段文字里,不同单词出现的次数
Beautiful is better than ugly Explicit is better than implicit Simple
is better than complex Complex is better than complicated Flat is
better than nested Sparse is better than dense
解法
para = '''
Beautiful is better than ugly Explicit is better than implicit Simple is better than complex Complex is better than complicated Flat is better than nested Sparse is better than dense
'''
# convert the string into the list
sentence = para.split()
# print(sentence)
a = set(sentence)
# using the set function to remove the same elements in the list
print(a)
for i in a:
count = sentence.count(i)
# The count () function is used to count the number of times an element appears in the list.
print(i, ' 出现的次数:', count)
尝试
看到这个题目,除了会把字符串转为列表,内心毫无思路,只好上网检索。查了半天,都是使用 counters, numpy之类的第三方库才能做出来。这可不行,安装这种第三方库可不容易。现在的坑还没爬出来,又跳进另一个深坑,不可取。
值得我看见这篇帖子 Python统计列表元素出现次数,里面提到的这两个方法,正是我想要的!虽然还有count()看不懂不会用,但是没关系。我先抄下来,然后再慢慢查。也就是一两个函数的问题,比安装numpy要简单。看懂了代码逻辑,上面的问题迎刃而解。
思考
不要怕难,不会就查。查到了还看不懂,就继续查。按照大佬所给出的知识点,再查。
比如你不理解 list=set(list) 是啥意思,那就继续查。用关键字【python set 列表】去查。
很多时候,硬着头皮再往前走几步,也许就会柳暗花明。
我不想21天从入门到放弃,我自己放弃太多次。
我想让自己赢一次,赢自己一次。