【问题标题】:Python : Count frequences in dictionaryPython:在字典中计算频率
【发布时间】:2016-12-02 13:12:14
【问题描述】:

我想计算字典中每个值的数量,并构造一个以该值作为键的新值,以及以所述值作为值的键列表。

Input :
b = {'a':3,'b':3,'c':8,'d':3,'e':8}
Output:
c = { '3':[a. b. d]
      '8':[c, e]
                    }

我已经写了以下内容,但是它引发了一个关键错误并且没有给出任何输出,有人可以帮忙吗?

def dictfreq(b):
    counter = dict()
    for k,v in b.iteritems():
        if v not in counter:
            counter[v].append(k)
        else:
            counter[v].append(k)

    return counter


print dictfreq(b)

【问题讨论】:

  • if v not in counter: - 如果计数器字典中没有v,你为什么要在下面一行? counter[v].append(something)?
  • 我知道你想自己实现这个,但只是为了记录:itertools 模块中有一个内置的计数器

标签: python python-2.7 list dictionary counter


【解决方案1】:

更好的方法是使用collections.defaultdict。例如:

from collections import defaultdict
b = {'a':3,'b':3,'c':8,'d':3,'e':8}

new_dict = defaultdict(list)  # `list` as default value
for k, v in b.items():
    new_dict[v].append(k)

new_dict 持有的最终值将是:

{8: ['c', 'e'], 3: ['a', 'b', 'd']}

【讨论】:

    【解决方案2】:

    改变这个

        if v not in counter:
            counter[v].append(k)
        else:
            counter[v].append(k)
    

    到这里:

        if v not in counter:
            counter[v] = []   # add empty `list` if value `v` is not found as key
        counter[v].append(k)
    

    【讨论】:

    • 这行得通,谢谢。这是我可以避免关键错误的一般方法吗?只需声明一个空字符串/列表/你有什么?
    • @onlyf 确实如此。像defaultdict 这样的其他解决方案正是在幕后完成的。
    • 好的,谢谢!对于像我这样的新人来说,这一直是一个头疼的问题。
    【解决方案3】:

    你可以使用dict.setdefault方法:

    >>> c =  {}
    >>> for key, value in b.iteritems():
    ...     c.setdefault(value, []).append(key)
    ...
    >>> c
    {8: ['c', 'e'], 3: ['a', 'b', 'd']}
    

    在 Python3 中,请改用 b.items()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-20
      • 1970-01-01
      • 2019-09-28
      • 2022-07-16
      • 2021-09-21
      • 2016-05-18
      相关资源
      最近更新 更多