我正在尝试在python中使用Counter方法,然后转换为字典。然而,元素列表非常大(约4200个元素)。所以这个函数应该打印元素和它的频率但是它给出了一个错误:ValueError: too many values to unpack (expected 2)
from collections import Counter
def contribution(competition):
users = Counter(['Filipe Andrew', 'M. B, Jnr, 'Retro P', 'Filipe Andrew', ...]) #up to 4200 elements
users_dict = dict(users)
for user, num_contribution in users_dict:
print(user, ' -> ', num_contribution)
contribution('year 2015_in_Brazil')```
items()方法返回一个视图对象。视图对象包含字典的键值对,就像列表中的元组一样。字典中的items方法返回一个字典项,即dict_items([('Filipe Andrew', 1), ('M. B, Jnr, 1), ('Retro P', 1)])
解决方案:
from collections import Counter
def contribution(competition):
users = Counter(['Filipe Andrew', 'M. B, Jnr, 'Retro P', 'Filipe Andrew', ...]) #up to 4200 elements
for user, num_contribution in users.items():
print(user, ' -> ', num_contribution)
contribution('year 2015_in_Brazil')