python-3.x 将Counter方法转换为字典返回错误

nukf8bse  于 2023-01-03  发布在  Python
关注(0)|答案(1)|浏览(148)

我正在python中尝试Counter方法,然后转换为dictionary。然而,元素列表非常大(~4200个元素)。因此,函数应该打印元素及其频率,但它给出了一个错误消息:值错误:要解包的值太多(应为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')```
gdrx4gfi

gdrx4gfi1#

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')

相关问题