python - 如何从 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)
提前致谢
解决方案
我明白你想做的事。我不确定这些“**”是否真的出现在您的回复中。我写了一个确实有效的例子。您只需要编写一个 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('___________________')
推荐阅读
- javascript - ReactJS 使用 onClick 调用两个函数
- javascript - 打印输入数据中最接近 0 的温度 - 编码游戏
- python - Github Rest API 返回重复值
- c# - 在 C# 中通过带有箭头键的文本框进行聚焦
- javascript - 修剪数组以删除 Javascript 中的空格
- python - 使用 GSuite API 读取域用户的电子邮件
- html - 什么是最好的网络托管服务
- java - 使用 gradle 的库 jar 的依赖项
- javascript - 如何修复赛普拉斯中错误的 API 请求?
- rich-text-editor - 将 Tinymce 添加到 Laravel 8