当前位置:   article > 正文

counts[word]=counts.get(word,0)+1_counts.get(word, 0) + 1

counts.get(word, 0) + 1

注:
counts[word] = counts.get(word,0)+1
是对进行计数word出现的频率进行统计,
当word不在words时,返回值是0,
当word在words中时,返回+1,
以此进行累计计数。

txt="a b c d a b c d a b c d"
print(txt)#a b c d a b c d a b c d
words=txt.split()#将每个字符按照空格分开
#就是将一个字符串分隔成多个字符串组成的列表(重复 有序)
print(words)#['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']

counts={}#新建1个字典
for word in words:#['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']
    counts[word]=counts.get(word,0)+1
    #print(counts.items())  
    print(list(counts.items()))#去除dict_items()包裹
    
#a b c d a b c d a b c d
#['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']
#[('a', 1)]
#[('a', 1), ('b', 1)]
#[('a', 1), ('b', 1), ('c', 1)]
#[('a', 1), ('b', 1), ('c', 1), ('d', 1)]
#[('a', 2), ('b', 1), ('c', 1), ('d', 1)]
#[('a', 2), ('b', 2), ('c', 1), ('d', 1)]
#[('a', 2), ('b', 2), ('c', 2), ('d', 1)]
#[('a', 2), ('b', 2), ('c', 2), ('d', 2)]
#[('a', 3), ('b', 2), ('c', 2), ('d', 2)]
#[('a', 3), ('b', 3), ('c', 2), ('d', 2)]
#[('a', 3), ('b', 3), ('c', 3), ('d', 2)]
#[('a', 3), ('b', 3), ('c', 3), ('d', 3)]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

counts[word]=counts.get(word,0)+1
一开始见到字典内的key的值:“a”,“b”,“c”,“d”,
因为之前没有遇到过,
所以就会给赋值后面的0.
对于前四个key:“a”,“b”,“c”,“d”
{"a":1,"b":1,"c":1,"d":1}
而对于第二轮的"a",“b”,“c”,“d”,
因为不是第一次见到了
所以不会赋给后面的值0,而是在他们key对应的value基础上+1
{"a":2,"b":2,"c":2,"d":2}
后面几轮的同理

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/109743
推荐阅读
相关标签
  

闽ICP备14008679号