【问题标题】:Shorting the code for update dictionary in python [duplicate]缩短python中更新字典的代码[重复]
【发布时间】:2018-05-14 21:56:30
【问题描述】:

如果数组中有一个元素并将其存储在字典中,是否有用于计算出现次数的当前代码的较短版本?

a = [1,2,2,3,4,5,2,2,1]
dic = {}
for x in a:
    if x in dic:
        dic[x] = dic[x] + 1
    else:
        dic[x] = 1

print dic

【问题讨论】:

  • 是的,使用collections.Counter

标签: python


【解决方案1】:

是的

您可以使用dictionary.get(key, default) 获取键的值,如果该键不存在,它会给出默认参数。

a = [1,2,2,3,4,5,2,2,1]
dic = {}

for n in a:
    dic[n] = dic.get(n, 0) + 1

【讨论】:

    【解决方案2】:

    你可以使用collections.Counter():

    from collections import Counter
    
    a = [1, 2, 2, 3, 4, 5, 2, 2, 1]
    dic = Counter(a)
    

    来自文档:

    Counterdict 子类,用于计算可散列对象。它是一个 无序集合,其中元素存储为字典键和 它们的计数存储为字典值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      • 2017-12-04
      相关资源
      最近更新 更多