首页 > 解决方案 > 从每行 json 数据返回 **unique** 计数

问题描述

我已经为此工作了一段时间,但似乎无法绕过它:我有一个看起来像这样的 JSON 数据块

0    [{'code': '8', 'name': 'Human development'}, {'code': '8', 'name': 'Human development'}
1    [{'code': '1', 'name': 'Economic management'},{'code': '8', 'name': 'Human development'}
2    [{'code': '5', 'name': 'Trade and integration'},{'code': '1', 'name': 'Economic management'}
3    [{'code': '7', 'name': 'Social dev/gender/inclusion'}]

我正在尝试生成每个值的计数,最后是这样的:

Human development : 2
Economic management : 2
Trade and integration : 1
Social dev/gender/inclusion : 1

注意:有些行编码两次(如第一行)应该只计算一次

我尝试了很多不同的东西,我最接近的是这个

for i in range(0,len(wbp['code'])):
# create a counter for the next step, counting the number of values of each subdict
number = len(wbp['code'][i])-1

#create empty values
dictd = dict()
lis = [] 

#iterate across the sublist 
for j in range (0,number):
    temp_list=[]
    temp_list.append(wbp['code'][i][int(j)]['name'])
    #using set to return only unique values
    lis = tuple(set(temp_list))
    if lis in dictd.keys():
        dictd[lis]+=1
    else:
        dictd[lis]=1
    #lis.append(temp_list)
    #value=[[x,lis.count(x)] for x in lis]
print(dictd)

返回:

{('Human development',): 1}
{('Economic management',): 1}
{('Trade and integration',): 1, ('Public sector governance',): 1, ('Environment and natural resources management',): 1}
{('Social dev/gender/inclusion',): 1}
{('Trade and integration',): 1}
{('Social protection and risk management',): 1}
{('Public sector governance',): 1}
{('Environment and natural resources management',): 1}
{('Rural development',): 1}
{('Public sector governance',): 2}
{('Rural development',): 1}
{('Rural development',): 1, ('Social protection and risk management',): 2}
{}
{('Trade and integration',): 1, ('Environment and natural resources management',): 1}
{('Social protection and risk management',): 2}
{('Rural development',): 1, ('Environment and natural resources management',): 1}
{('Rural development',): 1}
{('Human development',): 1}

这是不对的,因为它不是内部字典之外的工作计数器,这无论如何都不是我想要的。我所能想到的就是必须有一种更加pythonic的方式来做到这一点......

编辑:似乎我在清晰度方面做得很差:数据集中再次出现错误,因为第 0 行之类的条目有重复项。那些不应该被计算两次。人类发展的预期回报应该是 2,而不是 3,因为第一行是错误的。

标签: pythonpython-3.x

解决方案


由于输入细节不清楚,我假设您的输入如下所示,并附带以下代码:

    wbp = [[{'code': '8', 'name': 'Human development'}, {'code': '8', 'name': 'Human development'}],
       [{'code': '1', 'name': 'Economic management'}, {'code': '8', 'name': 'Human development'}],
       [{'code': '5', 'name': 'Trade and integration'}, {'code': '1', 'name': 'Economic management'}],
       [{'code': '7', 'name': 'Social dev/gender/inclusion'}]]

dictd = dict()

    for record in wbp:
        names = set([item['name'] for item in record]) # Remove duplicate names using set
        for name in names:
            dictd[name] = dictd.get(name, 0) + 1  # If name not found, then 0 + 1, else count + 1

    print(dictd)

这导致

{

'经济管理':2,

'社会发展/性别/包容':1,

'人类发展':2,

“贸易与一体化”:1

}


推荐阅读