【问题标题】:number of movies for each genre using dict python使用 dict python 的每种类型的电影数量
【发布时间】:2018-07-19 23:28:04
【问题描述】:

在我的代码中,我试图找出电影数据集中每种类型有多少部电影。找到了这个作为例子,但我找不到这个示例代码的解释。

from collections import Counter

 flattened_genres = [item for sublist in movies_df.genres_arr for item in 
sublist]

genre_dict = dict(Counter(flattened_genres))

print genre_dict

【问题讨论】:

    标签: python-3.x dictionary collections counter


    【解决方案1】:

    在不确切知道movies_df 数据集中的内容的情况下提供所有详细信息有些困难。但是......我最好的猜测是它是存储在子列表中的一系列电影类型。对于这个例子,我们大概可以认为它就像一个列表列表:

    [[romance, horror, thriller],
     [action, adventure, mystery],
     [horror, thriller, action],
     [romance, adventure, mystery]]
    

    以下行从collections 库中导入Counter 类。 Counter 类接受一系列项目并计算每个项目出现的数量。它将数据存储在Counter 对象中,该对象非常类似于具有一些额外功能(例如向您显示最常见项目的能力)的字典。

    from collections import Counter
    

    下一位挖掘流派数组中的每个子列表,并从每个子列表中提取每个项目并将它们转储到一个巨大的列表中。这是使用称为列表推导的语法完成的。这种从嵌套子列表中提取数据到单个列表中的技术称为扁平化。

    flattened_genres = [item for sublist in movies_df.genres_arr for item in sublist]
    

    另一种编写上述方法的方法是使用嵌套的 for 循环并将数据附加到主列表:

    flattened_genres = []
    for sublist in movies_df.genres_arr:
        for item in sublist:
            flattened_genres.append(item)
    

    列表推导通常比嵌套的 for 循环和附加函数调用具有更好的性能,但对于初学者来说往往更难理解,直到他们见过几次。

    展平的结果如下所示:

    [romance, horror, thriller, action, adventure, mystery, horror, thriller, action, romance, adventure, mystery]
    

    任何序列都可以输入Counter 以获取计数。使用这个简单的列表,我们可以计算所有的 'a' 和所有 'b' 等等。

    c = Counter(['a', 'b', 'c', 'b', 'a'])
    

    这产生了一个看起来像这样的Counter 对象,并表明它计算了两个'a'和两个'b',等等:

    >>> c
    Counter({'a': 2, 'b': 2, 'c': 1})
    

    Counter 对象与dicts 有点不同,所以如果你真的需要字典,可以通过dict 工厂函数运行Counter 来将其转换为字典来进行转换。在这种情况下,我们将 flattened_genres list 作为参数提供给 dict 工厂函数内的 Counter 类。

    genre_dict = dict(Counter(flattened_genres))
    

    最后,我们打印新字典。这个print 语句在Python 2 中使用。提供Python 版本3 的print() 函数是为了完整性:

    print genre_dict
    print(genre_dict)   # for those using Python 3
    

    【讨论】:

      猜你喜欢
      • 2020-03-24
      • 1970-01-01
      • 2023-03-07
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      • 2019-02-07
      相关资源
      最近更新 更多