【问题标题】:Count Occurrences of a Value in a List of Dictionaries计算字典列表中值的出现次数
【发布时间】:2014-11-15 00:24:32
【问题描述】:

我不知道我是否通常会以这种方式存储信息,但这是呈现给我的方式。

假设我有一个字典列表,其中记录了比方说不明飞行物目击事件的详细信息,看起来像这样:

aList = [{'country': 'japan', 'city': 'tokyo', 'year': 1995}, {'country': 'japan', 'city': 'hiroshima', 'year': 2005}, {'country': 'norway', 'city': 'oslo', 'year': 2005} ... etc]

我知道如何计算列表中出现的次数,但是涉及到字典,我不知道该怎么做。

例如,如果我想知道哪个国家/地区的 UFO 目击次数最多,我该怎么做?

【问题讨论】:

    标签: python list dictionary count


    【解决方案1】:

    您可以使用collections.Countergenerator expression 来计算每个国家/地区出现在列表中的次数。之后,您可以使用most_common 方法来获取出现最多的那个。代码将如下所示:

    from collections import Counter
    aList = [{'country': 'japan', 'city': 'tokyo', 'year': 1995}, {'country': 'japan', 'city': 'hiroshima', 'year': 2005}, {'country': 'norway', 'city': 'oslo', 'year': 2005}]
    
    [(country, _)] = Counter(x['country'] for x in aList).most_common(1)
    
    print(country)
    # Output: japan
    

    下面是每个部分的作用的演示:

    >>> from collections import Counter
    >>> aList = [{'country': 'japan', 'city': 'tokyo', 'year': '1995'}, {'country': 'japan', 'city': 'hiroshima', 'year': '2005'}, {'country': 'norway', 'city': 'oslo', 'year': '2005'}]
    >>> # Get all of the country names
    >>> [x['country'] for x in aList]
    ['japan', 'japan', 'norway']
    >>> # Total the names
    >>> Counter(x['country'] for x in aList)
    Counter({'japan': 2, 'norway': 1})
    >>> # Get the most common country
    >>> Counter(x['country'] for x in aList).most_common(1)
    [('japan', 2)]
    >>> # Use iterable unpacking to extract the country name
    >>> [(country, _)] = Counter(x['country'] for x in aList).most_common(1)
    >>> print(country)
    japan
    >>>
    

    【讨论】:

      【解决方案2】:

      这是一个简洁的版本:

      from collections import Counter
      from operator import itemgetter
      
      aList = [{'country': 'japan', 'city': 'tokyo', 'year': 1995}, {'country': 'japan', 'city': 'hiroshima', 'year': 2005}, {'country': 'norway', 'city': 'oslo', 'year': 2005}]
      
      countries = Counter(map(itemgetter('country'), aList))
      print countries.most_common()
      
      cities = Counter(map(itemgetter('city'), aList))
      print cities.most_common()
      

      输出

      [('japan', 2), ('norway', 1)]
      [('oslo', 1), ('hiroshima', 1), ('tokyo', 1)]
      

      【讨论】:

        猜你喜欢
        • 2021-12-04
        • 2022-11-23
        • 2016-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-25
        • 2018-06-30
        • 2012-10-05
        相关资源
        最近更新 更多