【问题标题】:get not working with dictionary comprehension不使用字典理解
【发布时间】:2020-12-26 21:46:44
【问题描述】:

创建一个包含给定字符串中每个字符出现频率的字典


    str1 = "peter piper picked a peck of pickled peppers"
    freq = {}
    freq2 = {}
    for c in str1:
        freq[c] = freq.get(c, 0) + 1
    freq2 = {c: freq2.get(c, 0) + 1 for c in str1}
    print(freq)
    print(freq2)

输出

{'p': 9, 'e': 8, 't': 1, 'r': 3, ' ': 7, 'i': 3, 'c': 3, 'k': 3, 'd': 2, 'a': 1, 'o': 1, 'f': 1, >'l': 1, 's': 1}

{'p': 1, 'e': 1, 't': 1, 'r': 1, ' ': 1, 'i': 1, 'c': 1, 'k': 1, 'd': 1, 'a': 1, 'o': 1, 'f': 1, >'l': 1, 's': 1}

我只是想知道为什么字典理解没有给我正确的答案?

【问题讨论】:

  • freq2.get(c, 0) 始终为0,新的freq2 dict 仅在 dict comphrneions 完成后绑定
  • 只是一种愚蠢但可能很有趣的其他方法:freq2.update((c, freq2.get(c, 0) + 1) for c in str1)
  • 顺便说一句:如果你有freq2 = { ...这样的行,那么你不需要之前的freq2 = {}
  • 您的意思是:freq2 = copy(freq)

标签: python python-3.x dictionary dictionary-comprehension


【解决方案1】:

当使用字典理解进行循环时,freq2 尚未更新,所有值都不存在,因此get 返回0(并且您添加1,因此分配给键的值是1 新词典)。

只有在字典推导之后,freq2 才会更新(使用字典推导创建的字典)。

步骤如下:

  1. 在第 5 行; freq2 为空
  2. 在第 6 行;首先,通过循环 freq2 空字典创建一个新字典。然后,将该新字典分配给freq2

【讨论】:

  • 欢迎@AayushGupta :)
猜你喜欢
  • 1970-01-01
  • 2018-04-07
  • 1970-01-01
  • 2018-06-21
  • 2021-01-04
  • 1970-01-01
  • 1970-01-01
  • 2021-07-24
  • 2016-09-03
相关资源
最近更新 更多