如何计算Python中字典中最常见的前10个值

2024-05-18

我对 python 和一般编程都很陌生,所以请友善。我正在尝试分析包含音乐信息的 csv 文件并返回最常听的前 n 个乐队。从下面的代码中,每听一首歌曲都是一个列表中的字典条目,格式如下:

[{'album': 'Exile on Main Street', 'song': 'Happy', 'datetime': '3 Dec 2014 14:08', 'artist': 'The Rolling Stones'}, {'album': 'II', 'song': 'Black Dog', 'datetime': '1 Dec 2014 08:08', 'artist': 'Led Zepplin'}]

from collections import Counter

def count_artist_plays(filename):
    with open(filename, 'r') as data:
        header = data.readline().strip().split(',')

        entries = []
        for line in data:
            entry = line.strip().split(',')
            listens = {}
            for info, type in enumerate(header):
                listens[type] = entry[info]

            entries.append(listens)

    for d in entries:
        arts = d['artist']
        c = Counter(arts)
        print c.most_common(10)

如何获得最常见的字符串(带)而不是像下面这样的字符细分?

[('s', 2), ('a', 1), (' ', 1), ('E', 1), ('l', 1), ('o', 1), ('n', 1), ('S', 1), ('v', 1), ('y', 1)]

初始化计数器一次,让keys成为艺术家,并在每次循环中增加一个键(艺术家):

c = Counter()
for d in entries:
    arts = d['artist']
    c[arts] += 1
print(c.most_common(10))

When arts是一个字符串,那么c = Counter(arts)计算其中的字符数arts:

In [522]: collections.Counter('Led Zepplin')
Out[522]: Counter({'e': 2, 'p': 2, ' ': 1, 'd': 1, 'i': 1, 'L': 1, 'l': 1, 'n': 1, 'Z': 1})

相比之下:

In [523]: c = collections.Counter()

In [524]: c['Led Zepplin'] += 1

In [525]: c['The Rolling Stones'] += 1

In [526]: c.most_common()
Out[526]: [('Led Zepplin', 1), ('The Rolling Stones', 1)]

或者,正如乔恩·克莱门茨(Jon Clements)指出的那样,建立一个所有艺术家的列表,然后计算列表:

c = Counter(d['artist'] for d in entries)
print(c.most_common(10))

请注意,上面使用了生成器表达式 http://docs.python.org/reference/expressions.html#generator-expressions避免构建(可能)大型临时列表,同时具有更简洁、可读的语法。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何计算Python中字典中最常见的前10个值 的相关文章