唐僧抽烟 2021-04-25 14:39 采纳率: 0%
浏览 21

py有关函数与字典的问题

article = '''This is a photograph of our village.
Our village is in a valley.
It is between two hills.
The village is on a river.
Here is another photograph of the village.
My wife and I are walking along the banks of the river.
We are on the left.
There is a boy in the water.
He is swimming across the river.
Here is another photograph.
This is the school building.
It is beside a park.
The park is on the right.
Some children are coming out of the building.
Some of them are going into the park.
'''
def get_word_count(article):
  count = {}
  word_list=article.lower().replace('.','').split()
  for word in word_list:
    if word in count:
      count[word] += 1
    else:
      count[word] = 1
  return count
print(get_word_count(article))

为啥定义的空字典但是在执行if语句时字典中已经有了内容呢?

各位大神求解!!!

  • 写回答

4条回答 默认 最新

  • 关注

       else:中不就是   count[word] = 1 对字典添加属性了么

     

        if word in count:

          count[word] += 1

        else:

          count[word] = 1

    这个if---else的意思就是:

    如果 word的值 在 count字典中,

    则count字典的word值的属性增加1

    否则就给 count字典中添加一个word值的属性并赋值为1。

     

    if---else是在for循环中重复执行的。

    当某个word值第一次出现时是,给字典中添加一个属性。

    当这个word值再次出现时,字典中就已经有了这个属性,就对这个属性增加1。

     

    评论

报告相同问题?

悬赏问题

  • ¥60 使用 STM32f103c6 微控制器设计两位计数器
  • ¥15 节日彩灯电路设计电路图
  • ¥15 esp32cam串口图传
  • ¥15 C# 用partial定义部分类无法快速预览代码
  • ¥15 fastreport 代码无法设置最后一页横线不显示
  • ¥15 stm32u535芯片usb hid custom类接收数据有问题
  • ¥15 ue5.3 pico打包失败 求帮助
  • ¥15 请教,这是用chatgpt写的CAD LISPD脚本,需求是画一个由双直线组成的矩形
  • ¥50 微信小程序 成功包奶茶啊
  • ¥15 计算机博弈的六子棋代码