【发布时间】:2021-09-16 23:11:34
【问题描述】:
我收到这样的输入:
input 1:
{
"name": "Ben",
"description": "Ben",
"attributes": [
{
"type": "Background",
"value": "Default"
},
{
"type": "Hair-color",
"value": "Brown"
}
]
}
input 2
{
"name": "Ice",
"description": "Ice",
"attributes": [
{
"type": "Background",
"value": "Green"
},
{
"type": "Hair-color",
"value": "White"
}
]
}
input 3
{
"name": "Itay",
"description": "Itay",
"attributes": [
{
"type": "Background",
"value": "Default"
},
{
"type": "Hair-color",
"value": "Brown"
}
]
}
我要做的是计算每种背景和每种发色出现的数量。 (这些是示例示例,实际上有更多类型和不同的值)
假设在这些示例中,我们有 2 个默认背景为背景的对象,那么我想要这样计数:
Backround default count=2
hair-color brown = 2
background green = 1
hair-color white = 1
我想要最有效的代码,因为代码还有其他方面,此外它会在数千个查询上运行,而不仅仅是两个,所以也需要在好的时候运行 :D 到目前为止我的代码:
import requests
import json
from collections import Counter
from collections import defaultdict
from time import sleep
attributes = []
test_dict = defaultdict(list)
for i in range(min_id, max_id+1):
api = 'api/v1/test/{}'.format(i)
response = requests.get(api)
item_dict = json.loads(response.text)
for item in item_dict['attributes']:
attributes.append(item["trait_type"]) if item["trait_type"] not in attributes else attributes
test_dict[item["trait_type"]].append(item["value"])
sleep(0.02)
for attribute in attributes:
print(attribute)
print(Counter(test_dict[attribute]))
【问题讨论】:
-
当你尝试这样做时发生了什么?你走了多远?出了什么问题?
-
我知道如何计算背景、头发颜色、默认值、棕色、绿色和白色出现的次数。我不知道/不知道如何将背景与默认和绿色以及头发颜色与棕色和白色相关联。
-
分享你的工作代码
-
@Sabil 我没有太多工作代码,主要是与 API 交互的基础。我想做的是创建一个像这样的字典:
{backround: default, count: 2}但这可能会使进一步的编码复杂化。最后,我想计算总对象的数量(在我们的例子中为 3),然后将每个值除以总数,看看它占总数的百分比。 -
我只是更新了我的答案,希望它能解决您的所有问题,包括比率计算。 :)
标签: python json formatting