首页 > 解决方案 > 如何从 dict 列表中获取前 3 个唯一名称并在 python 中计算它

问题描述

我有这样的回应,

resp = [{**"NR": "0"**,"Code": "4_RESOURCE","Cnt": "11"}, 
            {"NR": "10","Code": "10_humans","Cnt": "1"},
            {"NR": "1000","Code": "4_RESOURCE","Cnt": "120"}, 
            {**"NR": "0"**,"Code": "10_humans","Cnt": "12"},
             {**"NR": "0"**,"Code": "4_RESOURCE","Cnt": "15"},
             {**"NR": "0"**,"Code": "50_animals","Cnt": "20"}]

从中,如果“NR”是来自上述dict列表中唯一代码的“0”,则需要计算并将该计数与唯一代码相加。像那样需要取前三个计数输出样本:cnt计数,

"10_humans" = 12  (NR Zero)
"4_RESOURCE" = 15 (NE zero)
"50_animals" = 20 (NE Zero)

我试过了:

def se_conc(response):
    cnt = 0
    list = []

    def key_func(k):
         return k['Code']
   INFO = sorted(resp, key=y_func)
   for k, v in groupby(INFO, y_func):
            print("codes:", k)
            print("v:", v)
            list.append(k)
            print("listcode", list)

            for key in list:
                if resp['NR'] == "0":
                    print("NR is 0:", k)

提前致谢

标签: pythonpython-3.xlistdictionary

解决方案


我明白你想做的事。我不确定这些“**”是否真的出现在您的回复中。我写了一个确实有效的例子。您只需要编写一个 if 语句。我只是反复写它们以测试添加不同的响应。


NR_not_zero = 0
NE_not_zero = 0

if resposne['Code'] == "4_RESOURCE" and resposne['NR'] == '0':
    if resposne['NR'] == '0':
        NR_not_zero = NR_not_zero + int(resposne["Cnt"])
elif resposne['Code'] == "10_humans" and resposne['NR'] == '0':
    NE_not_zero = NE_not_zero + int(resposne["Cnt"])

print('NR = ',NR_not_zero)
print('NE = ',NE_not_zero)
print('___________________')

resposne = {"NR": "0","Code": "10_humans","Cnt": "12"}

if resposne['Code'] == "4_RESOURCE" and resposne['NR'] == '0':
    if resposne['NR'] == '0':
        NR_not_zero = NR_not_zero + int(resposne["Cnt"])
elif resposne['Code'] == "10_humans" and resposne['NR'] == '0':
    NE_not_zero = NE_not_zero + int(resposne["Cnt"])

print('NR = ',NR_not_zero)
print('NE = ',NE_not_zero)
print('___________________')


resposne = {"NR": "0","Code": "4_RESOURCE","Cnt": "15"}

if resposne['Code'] == "4_RESOURCE" and resposne['NR'] == '0':
    if resposne['NR'] == '0':
        NR_not_zero = NR_not_zero + int(resposne["Cnt"])
elif resposne['Code'] == "10_humans" and resposne['NR'] == '0':
    NE_not_zero = NE_not_zero + int(resposne["Cnt"])

print('NR = ',NR_not_zero)
print('NE = ',NE_not_zero)
print('___________________') 

resposne = {"NR": "0","Code": "10_humans","Cnt": "20"}

if resposne['Code'] == "4_RESOURCE" and resposne['NR'] == '0':
    if resposne['NR'] == '0':
        NR_not_zero = NR_not_zero + int(resposne["Cnt"])
elif resposne['Code'] == "10_humans" and resposne['NR'] == '0':
    NE_not_zero = NE_not_zero + int(resposne["Cnt"])

print('NR = ',NR_not_zero)
print('NE = ',NE_not_zero)
print('___________________') 



推荐阅读