【问题标题】:How do you count the occurrences of a value in a dictionary? [duplicate]如何计算字典中某个值的出现次数? [复制]
【发布时间】:2022-01-18 04:21:52
【问题描述】:

我正在尝试创建一个函数来计算每次字符串“在线”作为字典中的值出现时的计数。

例如,将以下字典输入到函数中应该得到 2,但我只得到 0。

statuses = {
"Alice": "online",
"Bob": "offline",
"Eve": "online",}

以下是我到目前为止的想法。这个函数只返回 0。我怎样才能让函数返回正确的计数?为什么返回 0?

def online_count(dict_a):
    count = 0
    for i in dict_a:
        if dict_a[i] == "online":
            count + 1
    return count

【问题讨论】:

  • @Skully 肯定是因为它是多年前发布的具有完全相同问题的帖子的副本。据我所知,它没有带来任何新的东西。

标签: python dictionary for-loop count


【解决方案1】:

您的解决方案是正确的!如果循环的当前索引处的值等于"online",则您在增加计数器方面有正确的想法,但是您实际上并没有增加count,您只是在添加它,尽管该表达式实际上不是保存到变量中。

count + 1

应该是:

count = count + 1

这样做的原因是你可以让count 等于它自己(它的当前计数器值),并且+1 来增加计数器。

为了进一步简化,你可以写count += 1,它做同样的事情。

最终代码:

statuses = {
    "Alice": "online",
    "Bob": "offline",
    "Eve": "online"
}

def online_count(dict_a):
    count = 0
    for i in dict_a:
        if dict_a[i] == "online":
            count += 1
    return count

【讨论】:

  • 谢谢!我是如此接近
【解决方案2】:

循环不会增加count - 它会将其与 1 相加,并忽略结果。你可以使用+= 来做到这一点:

count += 1

【讨论】:

    【解决方案3】:

    您需要确保函数中的行首先正确缩进。

    那你就用

    count + 1
    

    这将使计数值加 1 为零。

    您需要重新分配以计数

    count = count + 1
    

    或者是短版

    count += 1
    

    【讨论】:

      【解决方案4】:

      其他答案表明您的代码中的问题是您没有将新值分配给count。这是使用collections.Counter 容器的替代方法。

      >>> from collections import Counter
      >>> counts = Counter(statuses.values())
      >>> counts
      Counter({'online': 2, 'offline': 1})
      
      >> counts['online']
      2
      

      【讨论】:

        【解决方案5】:

        如果还有其他值并且您想放入字典中。

        import collections
        statuses = {
            "Alice": "online",
            "Bob": "offline",
            "Eve": "online",
            "Adam" : "1mn rest"
        }
        a = statuses.values()
        counter= collections.Counter(a)
        print(counter)
        

        【讨论】:

          猜你喜欢
          • 2018-06-30
          • 1970-01-01
          • 2023-03-27
          • 2016-09-23
          • 1970-01-01
          • 2021-11-25
          • 2019-07-13
          • 2013-02-24
          • 2013-12-25
          相关资源
          最近更新 更多